home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-04 / perl419x.zip / PERLDOS.MAN < prev    next >
Text File  |  1992-02-23  |  277KB  |  7,723 lines

  1.  
  2.  
  3.  
  4. PERL(1)                  USER COMMANDS                    PERL(1)
  5.  
  6.  
  7.  
  8. NNNNAAAAMMMMEEEE
  9.      perl - Practical Extraction and Report Language
  10.  
  11. SSSSYYYYNNNNOOOOPPPPSSSSIIIISSSS
  12.      ppppeeeerrrrllll [options] filename args
  13.  
  14. DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  15.      _P_e_r_l is an interpreted language optimized for scanning arbi-
  16.      trary  text  files,  extracting  information from those text
  17.      files, and printing reports based on that information.  It's
  18.      also  a good language for many system management tasks.  The
  19.      language is intended to be practical  (easy  to  use,  effi-
  20.      cient,  complete)  rather  than  beautiful  (tiny,  elegant,
  21.      minimal).  It combines (in  the  author's  opinion,  anyway)
  22.      some  of the best features of C, _s_e_d, _a_w_k, and _s_h, so people
  23.      familiar with those languages should have little  difficulty
  24.      with  it.  (Language historians will also note some vestiges
  25.      of _c_s_h, Pascal, and  even  BASIC-PLUS.)   Expression  syntax
  26.      corresponds  quite  closely  to C expression syntax.  Unlike
  27.      most Unix utilities, _p_e_r_l does  not  arbitrarily  limit  the
  28.      size  of your data--if you've got the memory, _p_e_r_l can slurp
  29.      in your whole file as a  single  string.   Recursion  is  of
  30.      unlimited  depth.   And  the hash tables used by associative
  31.      arrays grow as necessary to  prevent  degraded  performance.
  32.      _P_e_r_l  uses sophisticated pattern matching techniques to scan
  33.      large amounts of data very quickly.  Although optimized  for
  34.      scanning  text, _p_e_r_l can also deal with binary data, and can
  35.      make dbm files look like associative arrays  (where  dbm  is
  36.      available).   Setuid  _p_e_r_l scripts are safer than C programs
  37.      through a dataflow tracing  mechanism  which  prevents  many
  38.      stupid  security  holes.   If  you have a problem that would
  39.      ordinarily use _s_e_d or _a_w_k or _s_h, but it exceeds their  capa-
  40.      bilities  or must run a little faster, and you don't want to
  41.      write the silly thing in C, then _p_e_r_l may be for you.  There
  42.      are  also  translators to turn your _s_e_d and _a_w_k scripts into
  43.      _p_e_r_l scripts.  OK, enough hype.
  44.  
  45.      Note to MS-DOS users.   The MS-DOS version of _p_e_r_l  attempts
  46.      to  duplicate  the Unix version's functionality but is crip-
  47.      pled by MS-DOS and by the severe memory  limitations  MS-DOS
  48.      imposes.  The MS-DOS version is nevertheless useful for text
  49.      processing and for limited applications involving subprocess
  50.      management.   Refer to the section on MS-DOS CONSIDERATIONS.
  51.  
  52.  
  53.      Upon startup, _p_e_r_l looks for your script in one of the  fol-
  54.      lowing places:
  55.  
  56.      1.  Specified line by line via ----eeee switches  on  the  command
  57.          line.
  58.  
  59.      2.  Contained in the file specified by the first filename on
  60.  
  61.  
  62.  
  63. Consensys Computer Inc.                                         1
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. PERL(1)                  USER COMMANDS                    PERL(1)
  71.  
  72.  
  73.  
  74.          the  command line.  (Note that systems supporting the #!
  75.          notation invoke interpreters this way.)
  76.  
  77.      3.  Passed in implicitly  via  standard  input.   This  only
  78.          works  if there are no filename arguments--to pass argu-
  79.          ments to a _s_t_d_i_n script you must explicitly specify a  -
  80.          for the script name.
  81.  
  82.      After locating your script, _p_e_r_l compiles it to an  internal
  83.      form.   If  the  script is syntactically correct, it is exe-
  84.      cuted.
  85.  
  86.      OOOOppppttttiiiioooonnnnssss
  87.  
  88.      Note: on first reading this section may not make much  sense
  89.      to you.  It's here at the front for easy reference.
  90.  
  91.      A single-character option may be combined with the following
  92.      option, if any.  This is particularly useful when invoking a
  93.      script using the #! construct which only  allows  one  argu-
  94.      ment.  Example:
  95.  
  96.           #!/usr/bin/perl -spi.bak # same as -s -p -i.bak
  97.           ...
  98.  
  99.      Options include:
  100.  
  101.      ----0000_d_i_g_i_t_s
  102.           specifies the record separator ($/) as an octal number.
  103.           If  there  are  no  digits,  the  null character is the
  104.           separator.  Other switches may precede  or  follow  the
  105.           digits.   For  example,  if  you have a version of _f_i_n_d
  106.           which can print filenames terminated by the null  char-
  107.           acter, you can say this:
  108.  
  109.               find . -name '*.bak' -print0 | perl -n0e unlink
  110.  
  111.           The special value 00 will cause Perl to slurp files  in
  112.           paragraph  mode.   The  value  0777  will cause Perl to
  113.           slurp files whole since there  is  no  legal  character
  114.           with that value.
  115.  
  116.      ----aaaa   turns on autosplit mode when used with a ----nnnn or ----pppp.   An
  117.           implicit  split  command to the @F array is done as the
  118.           first thing inside the implicit while loop produced  by
  119.           the ----nnnn or ----pppp.
  120.  
  121.                perl -ane 'print pop(@F), "\n";'
  122.  
  123.           is equivalent to
  124.  
  125.                while (<>) {
  126.  
  127.  
  128.  
  129. Consensys Computer Inc.                                         2
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136. PERL(1)                  USER COMMANDS                    PERL(1)
  137.  
  138.  
  139.  
  140.                     @F = split(' ');
  141.                     print pop(@F), "\n";
  142.                }
  143.  
  144.  
  145.      ----cccc   causes _p_e_r_l to check the syntax of the script and  then
  146.           exit without executing it.
  147.  
  148.      ----dddd   runs the script under the perl debugger.  See the  sec-
  149.           tion on Debugging.
  150.  
  151.      ----DDDD_n_u_m_b_e_r
  152.           sets debugging flags.  To watch how  it  executes  your
  153.           script,  use  ----DDDD11114444.   (This  only works if debugging is
  154.           compiled  into  your  _p_e_r_l.)   Another  nice  value  is
  155.           -D1024,  which  lists  your  compiled syntax tree.  And
  156.           -D512 displays compiled regular expressions.
  157.  
  158.      ----eeee _c_o_m_m_a_n_d_l_i_n_e
  159.           may be used to enter one line of script.   Multiple  ----eeee
  160.           commands  may be given to build up a multi-line script.
  161.           If ----eeee is  given,  _p_e_r_l  will  not  look  for  a  script
  162.           filename  in  the  argument  list.   On  MS-DOS, the ----eeee
  163.           switch will not work well unless perl is  run  from  an
  164.           MKS tool, such as the Korn shell.  This is due to limi-
  165.           tations in the standard method of MS-DOS argument pass-
  166.           ing.
  167.  
  168.      ----iiii_e_x_t_e_n_s_i_o_n
  169.           specifies that files processed by the <> construct  are
  170.           to  be  edited  in-place.  It does this by renaming the
  171.           input file, opening the output file by the  same  name,
  172.           and selecting that output file as the default for print
  173.           statements.  The extension, if supplied,  is  added  to
  174.           the  name of the old file to make a backup copy.  If no
  175.           extension is supplied, no backup is made.  Saying "perl
  176.           -p  -i.bak  -e "s/foo/bar/;" ... " is the same as using
  177.           the script:
  178.  
  179.                #!/usr/bin/perl -pi.bak
  180.                s/foo/bar/;
  181.  
  182.           which is equivalent to
  183.  
  184.  
  185.  
  186.  
  187.  
  188.  
  189.  
  190.  
  191.  
  192.  
  193.  
  194.  
  195. Consensys Computer Inc.                                         3
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202. PERL(1)                  USER COMMANDS                    PERL(1)
  203.  
  204.  
  205.  
  206.                #!/usr/bin/perl
  207.                while (<>) {
  208.                     if ($ARGV ne $oldargv) {
  209.                          rename($ARGV, $ARGV . '.bak');
  210.                          open(ARGVOUT, ">$ARGV");
  211.                          select(ARGVOUT);
  212.                          $oldargv = $ARGV;
  213.                     }
  214.                     s/foo/bar/;
  215.                }
  216.                continue {
  217.                    print;     # this prints to original filename
  218.                }
  219.                select(STDOUT);
  220.  
  221.           except that the ----iiii form doesn't need to  compare  $ARGV
  222.           to  $oldargv to know when the filename has changed.  It
  223.           does, however, use ARGVOUT for the selected filehandle.
  224.           Note  that  _S_T_D_O_U_T  is  restored  as the default output
  225.           filehandle after the loop.
  226.  
  227.           You can use eof to locate the end of each  input  file,
  228.           in  case you want to append to each file, or reset line
  229.           numbering (see example under eof).
  230.  
  231.           On MS-DOS, and on OS/2 with the FAT filesystem,  simple
  232.           renaming  will rarely work and so _p_e_r_l uses a multiple-
  233.           try scheme.  The renaming described above is tried, and
  234.           if  it  works, fine.  If not, the following schemes are
  235.           tried in order.  If the suffix  begins  with  '.',  the
  236.           extension is replaced.  If the suffix is a single char-
  237.           acter, attempts are made to append  that  character  to
  238.           the   extension,   to  append  that  character  to  the
  239.           filename, to replace the last character of  the  exten-
  240.           sion,   and  to  replace  the  last  character  of  the
  241.           filename.  If all of these fail, attempts are  made  to
  242.           change the extension to "$$$", then "~~~".
  243.  
  244.      ----IIII_d_i_r_e_c_t_o_r_y
  245.           may be used in  conjunction  with  ----PPPP  to  tell  the  C
  246.           preprocessor  where  to  look  for  include  files.  By
  247.           default /usr/include and /usr/lib/perl are searched.
  248.  
  249.      ----llll_o_c_t_n_u_m
  250.           enables automatic line-ending processing.  It  has  two
  251.           effects:  first, it automatically chops the line termi-
  252.           nator when used with ----nnnn or ----pppp ,,,, and second, it  assigns
  253.           $\ to have the value of _o_c_t_n_u_m so that any print state-
  254.           ments will have that line terminator added back on.  If
  255.           _o_c_t_n_u_m  is omitted, sets $\ to the current value of $/.
  256.           For instance, to trim lines to 80 columns:
  257.  
  258.  
  259.  
  260.  
  261. Consensys Computer Inc.                                         4
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268. PERL(1)                  USER COMMANDS                    PERL(1)
  269.  
  270.  
  271.  
  272.                perl -lpe 'substr($_, 80) = ""'
  273.  
  274.           Note that the assignment $\  =  $/  is  done  when  the
  275.           switch  is processed, so the input record separator can
  276.           be different than the output record separator if the ----llll
  277.           switch is followed by a ----0000 switch:
  278.  
  279.                gnufind / -print0 | perl -ln0e 'print "found $_" if -p'
  280.  
  281.           This sets $\ to newline and then sets $/  to  the  null
  282.           character.
  283.  
  284.      ----nnnn   causes _p_e_r_l to assume the following  loop  around  your
  285.           script,  which makes it iterate over filename arguments
  286.           somewhat like "sed -n" or _a_w_k:
  287.  
  288.                while (<>) {
  289.                     ...       # your script goes here
  290.                }
  291.  
  292.           Note that the lines are not printed by default.  See ----pppp
  293.           to  have  lines  printed.   Here is an efficient way to
  294.           delete all files older than a week:
  295.  
  296.                find . -mtime +7 -print | perl -nle 'unlink;'
  297.  
  298.           This is faster than using  the  -exec  switch  of  find
  299.           because  you  don't  have  to  start a process on every
  300.           filename found.
  301.  
  302.      ----pppp   causes _p_e_r_l to assume the following  loop  around  your
  303.           script,  which makes it iterate over filename arguments
  304.           somewhat like _s_e_d:
  305.  
  306.                while (<>) {
  307.                     ...       # your script goes here
  308.                } continue {
  309.                     print;
  310.                }
  311.  
  312.           Note that the  lines  are  printed  automatically.   To
  313.           suppress  printing use the ----nnnn switch.  A ----pppp overrides a
  314.           ----nnnn switch.
  315.  
  316.      ----PPPP   causes your script to be run through the C preprocessor
  317.           before  compilation  by _p_e_r_l.  (Since both comments and
  318.           cpp directives begin with the # character,  you  should
  319.           avoid  starting  comments  with any words recognized by
  320.           the C preprocessor such as "if", "else"  or  "define".)
  321.           On  MS-DOS, the ----PPPP option is implemented using the perl
  322.           script _d_o_s_c_p_p._p_l.  This script must  be  found  in  the
  323.           first directory listed in @INC.  (see the @INC array in
  324.  
  325.  
  326.  
  327. Consensys Computer Inc.                                         5
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334. PERL(1)                  USER COMMANDS                    PERL(1)
  335.  
  336.  
  337.  
  338.           Predefined Names).  Currently the ----PPPP switch only  works
  339.           in  conjuction  with  Microsoft  C 6.0, but editing the
  340.           _d_o_s_c_p_p._p_l script may allow  its  use  with  other  com-
  341.           pilers.
  342.  
  343.      ----ssss   enables some rudimentary switch parsing for switches on
  344.           the  command  line after the script name but before any
  345.           filename arguments (or before a --).  Any switch  found
  346.           there  is removed from @ARGV and sets the corresponding
  347.           variable in the  _p_e_r_l  script.   The  following  script
  348.           prints "true" if and only if the script is invoked with
  349.           a -xyz switch.
  350.  
  351.                #!/usr/bin/perl -s
  352.                if ($xyz) { print "true\n"; }
  353.  
  354.  
  355.      ----SSSS   makes _p_e_r_l use the PATH environment variable to  search
  356.           for  the  script  (unless the name of the script starts
  357.           with a slash).  Typically this is used  to  emulate  #!
  358.           startup  on machines that don't support #!, in the fol-
  359.           lowing manner:
  360.  
  361.                #!/usr/bin/perl
  362.                eval "exec /usr/bin/perl -S $0 $*"
  363.                     if $running_under_some_shell;
  364.  
  365.           The system ignores the first line and feeds the  script
  366.           to  /bin/sh,  which proceeds to try to execute the _p_e_r_l
  367.           script as a  shell  script.   The  shell  executes  the
  368.           second  line as a normal shell command, and thus starts
  369.           up the _p_e_r_l interpreter.  On some  systems  $0  doesn't
  370.           always  contain the full pathname, so the ----SSSS tells _p_e_r_l
  371.           to search for the  script  if  necessary.   After  _p_e_r_l
  372.           locates  the  script,  it  parses the lines and ignores
  373.           them because the variable $running_under_some_shell  is
  374.           never  true.   A  better  construct  than  $*  would be
  375.           ${1+"$@"}, which handles embedded spaces  and  such  in
  376.           the  filenames, but doesn't work if the script is being
  377.           interpreted by csh.  In order to  start  up  sh  rather
  378.           than  csh, some systems may have to replace the #! line
  379.           with a line containing just a colon, which will be pol-
  380.           itely  ignored  by  perl.   Other systems can't control
  381.           that, and need a totally devious  construct  that  will
  382.           work  under any of csh, sh or perl, such as the follow-
  383.           ing:
  384.  
  385.                eval '(exit $?0)' && eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
  386.                & eval 'exec /usr/bin/perl -S $0 $argv:q'
  387.                     if 0;
  388.  
  389.            On MS-DOS, similar techniques can be used to create an
  390.  
  391.  
  392.  
  393. Consensys Computer Inc.                                         6
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. PERL(1)                  USER COMMANDS                    PERL(1)
  401.  
  402.  
  403.  
  404.           executable  batch  file or shell-script.   To create an
  405.           executable batch file, the following technique  can  be
  406.           used.
  407.  
  408.  
  409.                @REM=(qq!
  410.                @perl -S %0.bat %1 %2 %3 %4 %5 %6 %7 %8 %9
  411.                @goto end !) if 0 ;
  412.  
  413.                    # The perl script goes here.
  414.  
  415.                @REM=(qq!
  416.                :end !) if 0 ;
  417.  
  418.           Note that only nine arguments to perl can be passed  in
  419.           this  manner.   The four '!' characters can be replaced
  420.           with some untypeable character, such as  Ctrl-A.   This
  421.           will  allow  you to pass any characters, including ".."
  422.           strings as arguments.
  423.  
  424.           An MKS Korn shell script can be handled  almost  as  on
  425.           Unix.   Put  the  script into a file with the extension
  426.           ".ksh" and prepend the following.
  427.  
  428.                eval "exec /usr/bin/perl -S $0.ksh $*"
  429.                     if $running_under_some_shell;
  430.  
  431.  
  432.      ----uuuu   causes _p_e_r_l to dump core after compiling  your  script.
  433.           You  can  then  take this core dump and turn it into an
  434.           executable file by using the undump program  (not  sup-
  435.           plied).   This  speeds  startup  at the expense of some
  436.           disk space (which you can  minimize  by  stripping  the
  437.           executable).   (Still, a "hello world" executable comes
  438.           out to about 200K on my machine.)  If you are going  to
  439.           run your executable as a set-id program then you should
  440.           probably compile it using taintperl rather than  normal
  441.           perl.   If you want to execute a portion of your script
  442.           before dumping, use the dump operator  instead.   Note:
  443.           availability of undump is platform specific and may not
  444.           be available for a specific port of perl.   This switch
  445.           is not supported on MS-DOS.
  446.  
  447.      ----UUUU   allows _p_e_r_l to do  unsafe  operations.   Currently  the
  448.           only  "unsafe"  operations  are the unlinking of direc-
  449.           tories while running as superuser, and  running  setuid
  450.           programs  with fatal taint checks turned into warnings.
  451.           (Thse aren't applicable to MS-DOS.)
  452.  
  453.      ----vvvv   prints the version and patchlevel of your _p_e_r_l  execut-
  454.           able.
  455.  
  456.  
  457.  
  458.  
  459. Consensys Computer Inc.                                         7
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466. PERL(1)                  USER COMMANDS                    PERL(1)
  467.  
  468.  
  469.  
  470.      ----wwww   prints warnings about identifiers  that  are  mentioned
  471.           only  once,  and  scalar variables that are used before
  472.           being set.  Also warns about redefined subroutines, and
  473.           references  to  undefined  filehandles  or  filehandles
  474.           opened readonly that you are attempting  to  write  on.
  475.           Also  warns you if you use == on values that don't look
  476.           like numbers, and if your subroutines recurse more than
  477.           100 deep.
  478.  
  479.      ----xxxx_d_i_r_e_c_t_o_r_y
  480.           tells _p_e_r_l that the script is embedded  in  a  message.
  481.           Leading  garbage will be discarded until the first line
  482.           that starts with #! and  contains  the  string  "perl".
  483.           Any  meaningful  switches  on that line will be applied
  484.           (but only one group of switches, as with normal #! pro-
  485.           cessing).   If a directory name is specified, Perl will
  486.           switch to that directory  before  running  the  script.
  487.           The ----xxxx switch only controls the the disposal of leading
  488.           garbage.  The script must be terminated with __END__ if
  489.           there is trailing garbage to be ignored (the script can
  490.           process any or all of the trailing garbage via the DATA
  491.           filehandle if desired).
  492.  
  493.      DDDDaaaattttaaaa TTTTyyyyppppeeeessss aaaannnndddd OOOObbbbjjjjeeeeccccttttssss
  494.  
  495.      _P_e_r_l has three data types: scalars, arrays of  scalars,  and
  496.      associative arrays of scalars.  Normal arrays are indexed by
  497.      number, and associative arrays by string.
  498.  
  499.      The interpretation of operations and values  in  perl  some-
  500.      times  depends on the requirements of the context around the
  501.      operation or value.  There are three major contexts: string,
  502.      numeric  and  array.  Certain operations return array values
  503.      in contexts wanting an array, and scalar  values  otherwise.
  504.      (If this is true of an operation it will be mentioned in the
  505.      documentation for that operation.)  Operations which  return
  506.      scalars  don't  care  whether  the  context is looking for a
  507.      string or a number, but  scalar  variables  and  values  are
  508.      interpreted as strings or numbers as appropriate to the con-
  509.      text.  A scalar is interpreted as TRUE in the boolean  sense
  510.      if  it  is  not  the null string or 0.  Booleans returned by
  511.      operators are 1 for true and 0 or '' (the null  string)  for
  512.      false.
  513.  
  514.      There are actually two varieties of null string: defined and
  515.      undefined.   Undefined  null strings are returned when there
  516.      is no real value for something, such as when  there  was  an
  517.      error, or at end of file, or when you refer to an uninitial-
  518.      ized variable or element of an  array.   An  undefined  null
  519.      string  may become defined the first time you access it, but
  520.      prior to that you can use the defined() operator  to  deter-
  521.      mine whether the value is defined or not.
  522.  
  523.  
  524.  
  525. Consensys Computer Inc.                                         8
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532. PERL(1)                  USER COMMANDS                    PERL(1)
  533.  
  534.  
  535.  
  536.      References to scalar variables always begin with  '$',  even
  537.      when referring to a scalar that is part of an array.  Thus:
  538.  
  539.          $days           # a simple scalar variable
  540.          $days[28]       # 29th element of array @days
  541.          $days{'Feb'}    # one value from an associative array
  542.          $#days          # last index of array @days
  543.  
  544.      but entire arrays or array slices are denoted by '@':
  545.  
  546.          @days           # ($days[0], $days[1],... $days[n])
  547.          @days[3,4,5]    # same as @days[3..5]
  548.          @days{'a','c'}  # same as ($days{'a'},$days{'c'})
  549.  
  550.      and entire associative arrays are denoted by '%':
  551.  
  552.          %days           # (key1, val1, key2, val2 ...)
  553.  
  554.      Any of these eight constructs may serve as an  lvalue,  that
  555.      is,  may be assigned to.  (It also turns out that an assign-
  556.      ment is itself an lvalue in certain  contexts--see  examples
  557.      under s, tr and chop.)  Assignment to a scalar evaluates the
  558.      righthand side in a scalar context, while assignment  to  an
  559.      array  or  array  slice  evaluates  the righthand side in an
  560.      array context.
  561.  
  562.      You may  find  the  length  of  array  @days  by  evaluating
  563.      "$#days",  as in _c_s_h.  (Actually, it's not the length of the
  564.      array, it's the subscript of the last element,  since  there
  565.      is (ordinarily) a 0th element.)  Assigning to $#days changes
  566.      the length of the array.  Shortening an array by this method
  567.      does  not actually destroy any values.  Lengthening an array
  568.      that was previously shortened recovers the values that  were
  569.      in  those elements.  You can also gain some measure of effi-
  570.      ciency by preextending an array that is going  to  get  big.
  571.      (You  can  also  extend  an array by assigning to an element
  572.      that is off the end of the array.  This differs from assign-
  573.      ing to $#whatever in that intervening values are set to null
  574.      rather than recovered.)  You can truncate an array  down  to
  575.      nothing  by assigning the null list () to it.  The following
  576.      are exactly equivalent
  577.  
  578.           @whatever = ();
  579.           $#whatever = $[ - 1;
  580.  
  581.  
  582.      If you evaluate an array in a scalar context, it returns the
  583.      length of the array.  The following is always true:
  584.  
  585.           scalar(@whatever) == $#whatever - $[ + 1;
  586.  
  587.      If you evaluate an associative array in a scalar context, it
  588.  
  589.  
  590.  
  591. Consensys Computer Inc.                                         9
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598. PERL(1)                  USER COMMANDS                    PERL(1)
  599.  
  600.  
  601.  
  602.      returns  a value which is true if and only if the array con-
  603.      tains any elements.  (If there are any elements,  the  value
  604.      returned  is a string consisting of the number of used buck-
  605.      ets and the number of  allocated  buckets,  separated  by  a
  606.      slash.)
  607.  
  608.      Multi-dimensional arrays are not directly supported, but see
  609.      the  discussion of the $; variable later for a means of emu-
  610.      lating multiple subscripts with an associative  array.   You
  611.      could  also  write  a subroutine to turn multiple subscripts
  612.      into a single subscript.
  613.  
  614.      Every data type has its own  namespace.   You  can,  without
  615.      fear  of  conflict, use the same name for a scalar variable,
  616.      an array, an associative array, a filehandle,  a  subroutine
  617.      name,  and/or  a label.  Since variable and array references
  618.      always start with '$', '@', or  '%',  the  "reserved"  words
  619.      aren't  in  fact  reserved  with  respect to variable names.
  620.      (They ARE reserved with respect to labels  and  filehandles,
  621.      however,  which  don't  have  an  initial special character.
  622.      Hint:  you  could  say   open(LOG,'logfile')   rather   than
  623.      open(log,'logfile').    Using   uppercase  filehandles  also
  624.      improves readability and protects  you  from  conflict  with
  625.      future  reserved  words.)  Case IS significant--"FOO", "Foo"
  626.      and "foo" are all different names.  Names which start with a
  627.      letter may also contain digits and underscores.  Names which
  628.      do not start with a letter are  limited  to  one  character,
  629.      e.g.  "$%" or "$$".  (Most of the one character names have a
  630.      predefined significance to _p_e_r_l.  More later.)
  631.  
  632.      Numeric literals are specified in any of the usual  floating
  633.      point or integer formats:
  634.  
  635.          12345
  636.          12345.67
  637.          .23E-10
  638.          0xffff     # hex
  639.          0377  # octal
  640.  
  641.      String literals are delimited by  either  single  or  double
  642.      quotes.   They  work  much like shell quotes:  double-quoted
  643.      string literals are subject to backslash and  variable  sub-
  644.      stitution;  single-quoted strings are not (except for \' and
  645.      \\).  The usual backslash rules apply for making  characters
  646.      such  as  newline,  tab,  etc.,  as well as some more exotic
  647.      forms:
  648.  
  649.           \t        tab
  650.           \n        newline
  651.           \r        return
  652.           \f        form feed
  653.           \b        backspace
  654.  
  655.  
  656.  
  657. Consensys Computer Inc.                                        10
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664. PERL(1)                  USER COMMANDS                    PERL(1)
  665.  
  666.  
  667.  
  668.           \a        alarm (bell)
  669.           \e        escape
  670.           \033      octal char
  671.           \x1b      hex char
  672.           \c[       control char
  673.           \l        lowercase next char
  674.           \u        uppercase next char
  675.           \L        lowercase till \E
  676.           \U        uppercase till \E
  677.           \E        end case modification
  678.  
  679.      You can also embed newlines directly in your  strings,  i.e.
  680.      they  can  end on a different line than they begin.  This is
  681.      nice, but if you forget your trailing quote, the error  will
  682.      not be reported until _p_e_r_l finds another line containing the
  683.      quote character, which may be much further on in the script.
  684.      Variable  substitution  inside  strings is limited to scalar
  685.      variables, normal array values, and array slices.  (In other
  686.      words,  identifiers  beginning  with  $ or @, followed by an
  687.      optional bracketed expression as a subscript.)  The  follow-
  688.      ing code segment prints out "The price is $100."
  689.  
  690.          $Price = '$100';               # not interpreted
  691.          print "The price is $Price.\n";# interpreted
  692.  
  693.      Note that you can put curly brackets around  the  identifier
  694.      to  delimit it from following alphanumerics.  Also note that
  695.      a single quoted string must be separated  from  a  preceding
  696.      word  by a space, since single quote is a valid character in
  697.      an identifier (see Packages).
  698.  
  699.      Two  special  literals  are  __LINE__  and  __FILE__,  which
  700.      represent the current line number and filename at that point
  701.      in your program.  They may only be used as separate  tokens;
  702.      they  will  not  be interpolated into strings.  In addition,
  703.      the token __END__ may be used to indicate the logical end of
  704.      the  script  before  the  actual end of file.  Any following
  705.      text is ignored (but may be read via the  DATA  filehandle).
  706.      The  two  control  characters  ^D  and  ^Z  are synonyms for
  707.      __END__.
  708.  
  709.      A word that doesn't have any  other  interpretation  in  the
  710.      grammar  will  be  treated as if it had single quotes around
  711.      it.  For this purpose, a word consists only of  alphanumeric
  712.      characters  and underline, and must start with an alphabetic
  713.      character.  As with filehandles and labels, a bare word that
  714.      consists  entirely  of lowercase letters risks conflict with
  715.      future reserved words, and if you use the  ----wwww  switch,  Perl
  716.      will warn you about any such words.
  717.  
  718.      Array values are interpolated into double-quoted strings  by
  719.      joining  all  the  elements  of the array with the delimiter
  720.  
  721.  
  722.  
  723. Consensys Computer Inc.                                        11
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730. PERL(1)                  USER COMMANDS                    PERL(1)
  731.  
  732.  
  733.  
  734.      specified in the $" variable, space by default.   (Since  in
  735.      versions  of  perl  prior  to  3.0 the @ character was not a
  736.      metacharacter in double-quoted strings, the interpolation of
  737.      @array,   $array[EXPR],   @array[LIST],   $array{EXPR},   or
  738.      @array{LIST} only happens if array is  referenced  elsewhere
  739.      in  the  program  or  is  predefined.)   The  following  are
  740.      equivalent:
  741.  
  742.           $temp = join($",@ARGV);
  743.           system "echo $temp";
  744.  
  745.           system "echo @ARGV";
  746.  
  747.      Within search patterns (which  also  undergo  double-quotish
  748.      substitution)  there  is a bad ambiguity:  Is /$foo[bar]/ to
  749.      be interpreted as /${foo}[bar]/ (where [bar] is a  character
  750.      class for the regular expression) or as /${foo[bar]}/ (where
  751.      [bar] is the subscript to array @foo)?  If @foo doesn't oth-
  752.      erwise  exist,  then  it's  obviously a character class.  If
  753.      @foo exists, perl takes a good guess  about  [bar],  and  is
  754.      almost  always  right.  If it does guess wrong, or if you're
  755.      just plain paranoid, you can force the  correct  interpreta-
  756.      tion with curly brackets as above.
  757.  
  758.      A line-oriented form of quoting is based on the shell  here-
  759.      is syntax.  Following a << you specify a string to terminate
  760.      the quoted material, and all  lines  following  the  current
  761.      line  down  to  the  terminating string are the value of the
  762.      item.  The terminating string may be either an identifier (a
  763.      word),  or  some quoted text.  If quoted, the type of quotes
  764.      you use determines the treatment of the  text,  just  as  in
  765.      regular  quoting.   An unquoted identifier works like double
  766.      quotes.  There must be no space between the << and the iden-
  767.      tifier.   (If  you  put a space it will be treated as a null
  768.      identifier, which is valid,  and  matches  the  first  blank
  769.      line--see  Merry  Christmas example below.)  The terminating
  770.      string must appear by itself (unquoted and with no surround-
  771.      ing whitespace) on the terminating line.
  772.  
  773.           print <<EOF;        # same as above
  774.      The price is $Price.
  775.      EOF
  776.  
  777.           print <<"EOF";      # same as above
  778.      The price is $Price.
  779.      EOF
  780.  
  781.           print << x 10;      # null identifier is delimiter
  782.      Merry Christmas!
  783.  
  784.           print <<`EOC`;      # execute commands
  785.      echo hi there
  786.  
  787.  
  788.  
  789. Consensys Computer Inc.                                        12
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796. PERL(1)                  USER COMMANDS                    PERL(1)
  797.  
  798.  
  799.  
  800.      echo lo there
  801.      EOC
  802.  
  803.           print <<foo, <<bar; # you can stack them
  804.      I said foo.
  805.      foo
  806.      I said bar.
  807.      bar
  808.  
  809.      Array literals are denoted by separating  individual  values
  810.      by commas, and enclosing the list in parentheses:
  811.  
  812.           (LIST)
  813.  
  814.      In a context not requiring an array value, the value of  the
  815.      array literal is the value of the final element, as in the C
  816.      comma operator.  For example,
  817.  
  818.          @foo = ('cc', '-E', $bar);
  819.  
  820.      assigns the entire array value to array foo, but
  821.  
  822.          $foo = ('cc', '-E', $bar);
  823.  
  824.      assigns the value of variable bar  to  variable  foo.   Note
  825.      that the value of an actual array in a scalar context is the
  826.      length of the array; the following assigns to $foo the value
  827.      3:
  828.  
  829.          @foo = ('cc', '-E', $bar);
  830.          $foo = @foo;         # $foo gets 3
  831.  
  832.      You  may  have  an  optional  comma   before   the   closing
  833.      parenthesis of an array literal, so that you can say:
  834.  
  835.          @foo = (
  836.           1,
  837.           2,
  838.           3,
  839.          );
  840.  
  841.      When a LIST is  evaluated,  each  element  of  the  list  is
  842.      evaluated in an array context, and the resulting array value
  843.      is interpolated into LIST just as if each individual element
  844.      were a member of LIST.  Thus arrays lose their identity in a
  845.      LIST--the list
  846.  
  847.           (@foo,@bar,&SomeSub)
  848.  
  849.      contains all the elements of @foo followed by all  the  ele-
  850.      ments  of @bar, followed by all the elements returned by the
  851.      subroutine named SomeSub.
  852.  
  853.  
  854.  
  855. Consensys Computer Inc.                                        13
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862. PERL(1)                  USER COMMANDS                    PERL(1)
  863.  
  864.  
  865.  
  866.      A list value may also be subscripted like  a  normal  array.
  867.      Examples:
  868.  
  869.           $time = (stat($file))[8];     # stat returns array value
  870.           $digit = ('a','b','c','d','e','f')[$digit-10];
  871.           return (pop(@foo),pop(@foo))[0];
  872.  
  873.  
  874.      Array lists may be assigned to if and only if  each  element
  875.      of the list is an lvalue:
  876.  
  877.          ($a, $b, $c) = (1, 2, 3);
  878.  
  879.          ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
  880.  
  881.      The final element may be an array or an associative array:
  882.  
  883.          ($a, $b, @rest) = split;
  884.          local($a, $b, %rest) = @_;
  885.  
  886.      You can actually put an array anywhere in the list, but  the
  887.      first  array  in  the  list will soak up all the values, and
  888.      anything after it will get a null value.  This may be useful
  889.      in a local().
  890.  
  891.      An associative array literal contains pairs of values to  be
  892.      interpreted as a key and a value:
  893.  
  894.          # same as map assignment above
  895.          %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
  896.  
  897.      Array assignment in a scalar context returns the  number  of
  898.      elements produced by the expression on the right side of the
  899.      assignment:
  900.  
  901.           $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
  902.  
  903.  
  904.      There are several other pseudo-literals that you should know
  905.      about.    If  a  string  is  enclosed  by  backticks  (grave
  906.      accents), it first undergoes variable substitution just like
  907.      a  double  quoted  string.  It is then interpreted as a com-
  908.      mand, and the output of that command is  the  value  of  the
  909.      pseudo-literal,  like  in  a  shell.  In a scalar context, a
  910.      single string consisting of all the output is returned.   In
  911.      an  array  context,  an array of values is returned, one for
  912.      each line of output.  (You can set $/  to  use  a  different
  913.      line  terminator.)   The  command  is executed each time the
  914.      pseudo-literal is evaluated.  The status value of  the  com-
  915.      mand  is  returned  in  $?  (see  Predefined  Names  for the
  916.      interpretation of $?).  Unlike in  _c_s_h,  no  translation  is
  917.      done  on  the return data--newlines remain newlines.  Unlike
  918.  
  919.  
  920.  
  921. Consensys Computer Inc.                                        14
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928. PERL(1)                  USER COMMANDS                    PERL(1)
  929.  
  930.  
  931.  
  932.      in any of the shells, single quotes  do  not  hide  variable
  933.      names  in  the  command  from  interpretation.   To pass a $
  934.      through to the shell you need to hide it with a backslash.
  935.  
  936.      Evaluating a filehandle in angle brackets  yields  the  next
  937.      line  from  that file (newline included, so it's never false
  938.      until EOF, at which time an undefined  value  is  returned).
  939.      Ordinarily  you  must  assign  that value to a variable, but
  940.      there is one situation where an  automatic  assignment  hap-
  941.      pens.   If  (and only if) the input symbol is the only thing
  942.      inside the  conditional  of  a  _w_h_i_l_e  loop,  the  value  is
  943.      automatically assigned to the variable "$_".  (This may seem
  944.      like an odd thing to you, but you'll use  the  construct  in
  945.      almost  every _p_e_r_l script you write.)  Anyway, the following
  946.      lines are equivalent to each other:
  947.  
  948.          while ($_ = <STDIN>) { print; }
  949.          while (<STDIN>) { print; }
  950.          for (;<STDIN>;) { print; }
  951.          print while $_ = <STDIN>;
  952.          print while <STDIN>;
  953.  
  954.      The filehandles _S_T_D_I_N, _S_T_D_O_U_T  and  _S_T_D_E_R_R  are  predefined.
  955.      (The  filehandles  _s_t_d_i_n,  _s_t_d_o_u_t  and _s_t_d_e_r_r will also work
  956.      except in packages, where they would be interpreted as local
  957.      identifiers rather than global.)  Additional filehandles may
  958.      be created with the _o_p_e_n function.
  959.  
  960.      If a <FILEHANDLE> is used in a context that is  looking  for
  961.      an  array,  an  array  consisting  of all the input lines is
  962.      returned, one line per array element.  It's easy to  make  a
  963.      LARGE data space this way, so use with care.
  964.  
  965.      The null filehandle <> is special and can be used to emulate
  966.      the  behavior  of  _s_e_d  and _a_w_k.  Input from <> comes either
  967.      from standard input, or from each file listed on the command
  968.      line.   Here's how it works: the first time <> is evaluated,
  969.      the ARGV array is checked, and if it is  null,  $ARGV[0]  is
  970.      set to '-', which when opened gives you standard input.  The
  971.      ARGV array is then processed as a list  of  filenames.   The
  972.      loop
  973.  
  974.           while (<>) {
  975.                ...            # code for each line
  976.           }
  977.  
  978.  
  979.  
  980.  
  981.  
  982.  
  983.  
  984.  
  985.  
  986.  
  987. Consensys Computer Inc.                                        15
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994. PERL(1)                  USER COMMANDS                    PERL(1)
  995.  
  996.  
  997.  
  998.      is equivalent to
  999.  
  1000.           unshift(@ARGV, '-') if $#ARGV < $[;
  1001.           while ($ARGV = shift) {
  1002.                open(ARGV, $ARGV);
  1003.                while (<ARGV>) {
  1004.                     ...       # code for each line
  1005.                }
  1006.           }
  1007.  
  1008.      except that it isn't as cumbersome to say.  It  really  does
  1009.      shift  array ARGV and put the current filename into variable
  1010.      ARGV.  It also uses filehandle  ARGV  internally.   You  can
  1011.      modify  @ARGV  before  the first <> as long as you leave the
  1012.      first filename at the beginning of the array.  Line  numbers
  1013.      ($.)  continue as if the input was one big happy file.  (But
  1014.      see example under eof for how to reset line numbers on  each
  1015.      file.)
  1016.  
  1017.      If you want to set @ARGV to your own list of files, go right
  1018.      ahead.   If  you want to pass switches into your script, you
  1019.      can put a loop on the front like this:
  1020.  
  1021.           while ($_ = $ARGV[0], /^-/) {
  1022.                shift;
  1023.               last if /^--$/;
  1024.                /^-D(.*)/ && ($debug = $1);
  1025.                /^-v/ && $verbose++;
  1026.                ...       # other switches
  1027.           }
  1028.           while (<>) {
  1029.                ...       # code for each line
  1030.           }
  1031.  
  1032.      The <> symbol will return FALSE only once.  If you  call  it
  1033.      again  after  this it will assume you are processing another
  1034.      @ARGV list, and if you haven't set @ARGV,  will  input  from
  1035.      _S_T_D_I_N.
  1036.  
  1037.      If the string inside the angle brackets is a reference to  a
  1038.      scalar  variable  (e.g. <$foo>), then that variable contains
  1039.      the name of the filehandle to input from.
  1040.  
  1041.      If the string inside angle brackets is not a filehandle,  it
  1042.      is  interpreted  as  a  filename  pattern to be globbed, and
  1043.      either an array of filenames or the  next  filename  in  the
  1044.      list  is  returned,  depending  on  context.  One level of $
  1045.      interpretation is done  first,  but  you  can't  say  <$foo>
  1046.      because  that's  an  indirect filehandle as explained in the
  1047.      previous paragraph.  You  could  insert  curly  brackets  to
  1048.      force interpretation as a filename glob: <${foo}>.  Example:
  1049.  
  1050.  
  1051.  
  1052.  
  1053. Consensys Computer Inc.                                        16
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060. PERL(1)                  USER COMMANDS                    PERL(1)
  1061.  
  1062.  
  1063.  
  1064.           while (<*.c>) {
  1065.                chmod 0644, $_;
  1066.           }
  1067.  
  1068.      is equivalent to
  1069.  
  1070.           open(foo, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
  1071.           while (<foo>) {
  1072.                chop;
  1073.                chmod 0644, $_;
  1074.           }
  1075.  
  1076.      In fact, it's currently implemented that way.  (Which  means
  1077.      it will not work on filenames with spaces in them unless you
  1078.      have /bin/csh on your machine.)  Of course, the shortest way
  1079.      to do the above is:
  1080.  
  1081.           chmod 0644, <*.c>;
  1082.  
  1083.  
  1084.      SSSSyyyynnnnttttaaaaxxxx
  1085.  
  1086.      A _p_e_r_l script consists of a  sequence  of  declarations  and
  1087.      commands.   The only things that need to be declared in _p_e_r_l
  1088.      are report formats and subroutines.  See the sections  below
  1089.      for  more information on those declarations.  All uninitial-
  1090.      ized user-created objects are assumed to start with  a  null
  1091.      or 0 value until they are defined by some explicit operation
  1092.      such as assignment.  The sequence of  commands  is  executed
  1093.      just once, unlike in _s_e_d and _a_w_k scripts, where the sequence
  1094.      of commands is executed for each  input  line.   While  this
  1095.      means  that  you must explicitly loop over the lines of your
  1096.      input file (or files), it also means you have much more con-
  1097.      trol  over  which files and which lines you look at.  (Actu-
  1098.      ally, I'm lying--it is possible to do an implicit loop  with
  1099.      either the ----nnnn or ----pppp switch.)
  1100.  
  1101.      A declaration can be put anywhere a command can, but has  no
  1102.      effect   on   the  execution  of  the  primary  sequence  of
  1103.      commands--declarations all  take  effect  at  compile  time.
  1104.      Typically  all  the declarations are put at the beginning or
  1105.      the end of the script.
  1106.  
  1107.      _P_e_r_l is, for the most part, a free-form language.  (The only
  1108.      exception to this is format declarations, for fairly obvious
  1109.      reasons.)  Comments are indicated by the  #  character,  and
  1110.      extend  to the end of the line.  If you attempt to use /* */
  1111.      C comments, it will be interpreted  either  as  division  or
  1112.      pattern  matching,  depending  on  the context.  So don't do
  1113.      that.
  1114.  
  1115.  
  1116.  
  1117.  
  1118.  
  1119. Consensys Computer Inc.                                        17
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126. PERL(1)                  USER COMMANDS                    PERL(1)
  1127.  
  1128.  
  1129.  
  1130.      CCCCoooommmmppppoooouuuunnnndddd ssssttttaaaatttteeeemmmmeeeennnnttttssss
  1131.  
  1132.      In _p_e_r_l, a sequence of commands may be treated as  one  com-
  1133.      mand by enclosing it in curly brackets.  We will call this a
  1134.      BLOCK.
  1135.  
  1136.      The following compound commands may be used to control flow:
  1137.  
  1138.           if (EXPR) BLOCK
  1139.           if (EXPR) BLOCK else BLOCK
  1140.           if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
  1141.           LABEL while (EXPR) BLOCK
  1142.           LABEL while (EXPR) BLOCK continue BLOCK
  1143.           LABEL for (EXPR; EXPR; EXPR) BLOCK
  1144.           LABEL foreach VAR (ARRAY) BLOCK
  1145.           LABEL BLOCK continue BLOCK
  1146.  
  1147.      Note that, unlike C and Pascal, these are defined  in  terms
  1148.      of BLOCKs, not statements.  This means that the curly brack-
  1149.      ets are _r_e_q_u_i_r_e_d--no dangling statements  allowed.   If  you
  1150.      want  to write conditionals without curly brackets there are
  1151.      several other ways to do it.  The following all do the  same
  1152.      thing:
  1153.  
  1154.           if (!open(foo)) { die "Can't open $foo: $!"; }
  1155.           die "Can't open $foo: $!" unless open(foo);
  1156.           open(foo) || die "Can't open $foo: $!"; # foo or bust!
  1157.           open(foo) ? 'hi mom' : die "Can't open $foo: $!";
  1158.                          # a bit exotic, that last one
  1159.  
  1160.  
  1161.      The _i_f  statement  is  straightforward.   Since  BLOCKs  are
  1162.      always  bounded  by curly brackets, there is never any ambi-
  1163.      guity about which _i_f an _e_l_s_e goes with.  If you  use  _u_n_l_e_s_s
  1164.      in place of _i_f, the sense of the test is reversed.
  1165.  
  1166.      The _w_h_i_l_e statement  executes  the  block  as  long  as  the
  1167.      expression  is true (does not evaluate to the null string or
  1168.      0).  The LABEL is optional, and if present, consists  of  an
  1169.      identifier  followed  by  a colon.  The LABEL identifies the
  1170.      loop for the loop control statements _n_e_x_t,  _l_a_s_t,  and  _r_e_d_o
  1171.      (see  below).   If  there  is a _c_o_n_t_i_n_u_e BLOCK, it is always
  1172.      executed  just  before  the  conditional  is  about  to   be
  1173.      evaluated  again,  similarly to the third part of a _f_o_r loop
  1174.      in C.  Thus it can be used to  increment  a  loop  variable,
  1175.      even when the loop has been continued via the _n_e_x_t statement
  1176.      (similar to the C "continue" statement).
  1177.  
  1178.      If the word _w_h_i_l_e is replaced by the word _u_n_t_i_l,  the  sense
  1179.      of the test is reversed, but the conditional is still tested
  1180.      before the first iteration.
  1181.  
  1182.  
  1183.  
  1184.  
  1185. Consensys Computer Inc.                                        18
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192. PERL(1)                  USER COMMANDS                    PERL(1)
  1193.  
  1194.  
  1195.  
  1196.      In either the _i_f or the _w_h_i_l_e  statement,  you  may  replace
  1197.      "(EXPR)"  with  a  BLOCK, and the conditional is true if the
  1198.      value of the last command in that block is true.
  1199.  
  1200.      The _f_o_r loop works  exactly  like  the  corresponding  _w_h_i_l_e
  1201.      loop:
  1202.  
  1203.           for ($i = 1; $i < 10; $i++) {
  1204.                ...
  1205.           }
  1206.  
  1207.      is the same as
  1208.  
  1209.           $i = 1;
  1210.           while ($i < 10) {
  1211.                ...
  1212.           } continue {
  1213.                $i++;
  1214.           }
  1215.  
  1216.      The foreach loop iterates over a normal array value and sets
  1217.      the  variable  VAR  to be each element of the array in turn.
  1218.      The variable is implicitly local to the  loop,  and  regains
  1219.      its  former value upon exiting the loop.  The "foreach" key-
  1220.      word is actually identical to the "for" keyword, so you  can
  1221.      use  "foreach" for readability or "for" for brevity.  If VAR
  1222.      is omitted, $_ is set to each value.  If ARRAY is an  actual
  1223.      array  (as  opposed  to  an  expression  returning  an array
  1224.      value), you can modify each element of the array by  modify-
  1225.      ing VAR inside the loop.  Examples:
  1226.  
  1227.           for (@ary) { s/foo/bar/; }
  1228.  
  1229.           foreach $elem (@elements) {
  1230.                $elem *= 2;
  1231.           }
  1232.  
  1233.           for ((10,9,8,7,6,5,4,3,2,1,'BOOM')) {
  1234.                print $_, "\n"; sleep(1);
  1235.           }
  1236.  
  1237.           for (1..15) { print "Merry Christmas\n"; }
  1238.  
  1239.           foreach $item (split(/:[\\\n:]*/, $ENV{'TERMCAP'})) {
  1240.                print "Item: $item\n";
  1241.           }
  1242.  
  1243.  
  1244.      The BLOCK by itself (labeled or not) is equivalent to a loop
  1245.      that  executes  once.  Thus you can use any of the loop con-
  1246.      trol statements in it to leave or restart  the  block.   The
  1247.      _c_o_n_t_i_n_u_e  block is optional.  This construct is particularly
  1248.  
  1249.  
  1250.  
  1251. Consensys Computer Inc.                                        19
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258. PERL(1)                  USER COMMANDS                    PERL(1)
  1259.  
  1260.  
  1261.  
  1262.      nice for doing case structures.
  1263.  
  1264.           foo: {
  1265.                if (/^abc/) { $abc = 1; last foo; }
  1266.                if (/^def/) { $def = 1; last foo; }
  1267.                if (/^xyz/) { $xyz = 1; last foo; }
  1268.                $nothing = 1;
  1269.           }
  1270.  
  1271.      There is no official switch statement in perl, because there
  1272.      are  already several ways to write the equivalent.  In addi-
  1273.      tion to the above, you could write
  1274.  
  1275.           foo: {
  1276.                $abc = 1, last foo  if /^abc/;
  1277.                $def = 1, last foo  if /^def/;
  1278.                $xyz = 1, last foo  if /^xyz/;
  1279.                $nothing = 1;
  1280.           }
  1281.  
  1282.      or
  1283.  
  1284.           foo: {
  1285.                /^abc/ && do { $abc = 1; last foo; };
  1286.                /^def/ && do { $def = 1; last foo; };
  1287.                /^xyz/ && do { $xyz = 1; last foo; };
  1288.                $nothing = 1;
  1289.           }
  1290.  
  1291.      or
  1292.  
  1293.           foo: {
  1294.                /^abc/ && ($abc = 1, last foo);
  1295.                /^def/ && ($def = 1, last foo);
  1296.                /^xyz/ && ($xyz = 1, last foo);
  1297.                $nothing = 1;
  1298.           }
  1299.  
  1300.      or even
  1301.  
  1302.           if (/^abc/)
  1303.                { $abc = 1; }
  1304.           elsif (/^def/)
  1305.                { $def = 1; }
  1306.           elsif (/^xyz/)
  1307.                { $xyz = 1; }
  1308.           else
  1309.                {$nothing = 1;}
  1310.  
  1311.      As it happens, these  are  all  optimized  internally  to  a
  1312.      switch  structure,  so  perl  jumps  directly to the desired
  1313.      statement, and you needn't worry about perl executing a  lot
  1314.  
  1315.  
  1316.  
  1317. Consensys Computer Inc.                                        20
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324. PERL(1)                  USER COMMANDS                    PERL(1)
  1325.  
  1326.  
  1327.  
  1328.      of  unnecessary  statements  when  you  have  a string of 50
  1329.      elsifs, as long as you are testing the  same  simple  scalar
  1330.      variable  using  ==,  eq, or pattern matching as above.  (If
  1331.      you're curious as to whether the optimizer has done this for
  1332.      a  particular  case statement, you can use the -D1024 switch
  1333.      to list the syntax tree before execution.)
  1334.  
  1335.      SSSSiiiimmmmpppplllleeee ssssttttaaaatttteeeemmmmeeeennnnttttssss
  1336.  
  1337.      The only kind of simple statement is an expression evaluated
  1338.      for  its  side effects.  Every expression (simple statement)
  1339.      must be terminated with a semicolon.  Note that this is like
  1340.      C, but unlike Pascal (and _a_w_k).
  1341.  
  1342.      Any simple statement may optionally be followed by a  single
  1343.      modifier, just before the terminating semicolon.  The possi-
  1344.      ble modifiers are:
  1345.  
  1346.           if EXPR
  1347.           unless EXPR
  1348.           while EXPR
  1349.           until EXPR
  1350.  
  1351.      The _i_f and _u_n_l_e_s_s modifiers  have  the  expected  semantics.
  1352.      The  _w_h_i_l_e and _u_n_t_i_l modifiers also have the expected seman-
  1353.      tics (conditional evaluated first), except when applied to a
  1354.      do-BLOCK or a do-SUBROUTINE command, in which case the block
  1355.      executes once before the conditional is evaluated.  This  is
  1356.      so that you can write loops like:
  1357.  
  1358.           do {
  1359.                $_ = <STDIN>;
  1360.                ...
  1361.           } until $_ eq ".\n";
  1362.  
  1363.      (See the _d_o operator below.  Note also that the loop control
  1364.      commands  described  later  will NOT work in this construct,
  1365.      since modifiers don't take loop labels.  Sorry.)
  1366.  
  1367.      EEEExxxxpppprrrreeeessssssssiiiioooonnnnssss
  1368.  
  1369.      Since _p_e_r_l expressions work almost exactly  like  C  expres-
  1370.      sions, only the differences will be mentioned here.
  1371.  
  1372.      Here's what _p_e_r_l has that C doesn't:
  1373.  
  1374.      **      The exponentiation operator.
  1375.  
  1376.      **=     The exponentiation assignment operator.
  1377.  
  1378.      ()      The null list, used to initialize an array to null.
  1379.  
  1380.  
  1381.  
  1382.  
  1383. Consensys Computer Inc.                                        21
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390. PERL(1)                  USER COMMANDS                    PERL(1)
  1391.  
  1392.  
  1393.  
  1394.      .       Concatenation of two strings.
  1395.  
  1396.      .=      The concatenation assignment operator.
  1397.  
  1398.      eq      String equality (== is  numeric  equality).   For  a
  1399.              mnemonic  just  think  of "eq" as a string.  (If you
  1400.              are used to the _a_w_k behavior of using == for  either
  1401.              string or numeric equality based on the current form
  1402.              of the comparands, beware!   You  must  be  explicit
  1403.              here.)
  1404.  
  1405.      ne      String inequality (!= is numeric inequality).
  1406.  
  1407.      lt      String less than.
  1408.  
  1409.      gt      String greater than.
  1410.  
  1411.      le      String less than or equal.
  1412.  
  1413.      ge      String greater than or equal.
  1414.  
  1415.      cmp     String comparison, returning -1, 0, or 1.
  1416.  
  1417.      <=>     Numeric comparison, returning -1, 0, or 1.
  1418.  
  1419.      =~      Certain operations search or modify the string  "$_"
  1420.              by default.  This operator makes that kind of opera-
  1421.              tion work on some other string.  The right  argument
  1422.              is  a  search pattern, substitution, or translation.
  1423.              The  left  argument  is  what  is  supposed  to   be
  1424.              searched,  substituted, or translated instead of the
  1425.              default "$_".  The return value indicates  the  suc-
  1426.              cess of the operation.  (If the right argument is an
  1427.              expression other than a  search  pattern,  substitu-
  1428.              tion,  or translation, it is interpreted as a search
  1429.              pattern at run time.  This is less efficient than an
  1430.              explicit  search, since the pattern must be compiled
  1431.              every time the expression is evaluated.)   The  pre-
  1432.              cedence  of  this operator is lower than unary minus
  1433.              and autoincrement/decrement, but higher than  every-
  1434.              thing else.
  1435.  
  1436.      !~      Just like =~ except the return value is negated.
  1437.  
  1438.      x       The repetition operator.  Returns a string  consist-
  1439.              ing of the left operand repeated the number of times
  1440.              specified by the right operand.  In  an  array  con-
  1441.              text,  if  the  left operand is a list in parens, it
  1442.              repeats the list.
  1443.  
  1444.                   print '-' x 80;          # print row of dashes
  1445.                   print '-' x80;      # illegal, x80 is identifier
  1446.  
  1447.  
  1448.  
  1449. Consensys Computer Inc.                                        22
  1450.  
  1451.  
  1452.  
  1453.  
  1454.  
  1455.  
  1456. PERL(1)                  USER COMMANDS                    PERL(1)
  1457.  
  1458.  
  1459.  
  1460.                   print "\t" x ($tab/8), ' ' x ($tab%8);  # tab over
  1461.  
  1462.                   @ones = (1) x 80;        # an array of 80 1's
  1463.                   @ones = (5) x @ones;          # set all elements to 5
  1464.  
  1465.  
  1466.      x=      The repetition assignment operator.  Only  works  on
  1467.              scalars.
  1468.  
  1469.      ..      The range operator, which is  really  two  different
  1470.              operators  depending  on  the  context.  In an array
  1471.              context, returns an array  of  values  counting  (by
  1472.              ones)  from the left value to the right value.  This
  1473.              is useful for writing "for (1..10)"  loops  and  for
  1474.              doing slice operations on arrays.
  1475.  
  1476.              In a scalar context, ..  returns  a  boolean  value.
  1477.              The  operator  is bistable, like a flip-flop..  Each
  1478.              .. operator maintains its own boolean state.  It  is
  1479.              false  as  long  as its left operand is false.  Once
  1480.              the left operand is true, the range  operator  stays
  1481.              true  until  the  right operand is true, AFTER which
  1482.              the range operator becomes false again.  (It doesn't
  1483.              become  false  till the next time the range operator
  1484.              is evaluated.  It  can  become  false  on  the  same
  1485.              evaluation it became true, but it still returns true
  1486.              once.)  The right operand is not evaluated while the
  1487.              operator  is  in  the  "false"  state,  and the left
  1488.              operand is not evaluated while the  operator  is  in
  1489.              the  "true"  state.   The scalar .. operator is pri-
  1490.              marily intended for doing line number  ranges  after
  1491.              the fashion of _s_e_d or _a_w_k.  The precedence is a lit-
  1492.              tle lower than || and &&.   The  value  returned  is
  1493.              either  the  null  string  for  false, or a sequence
  1494.              number (beginning with 1) for  true.   The  sequence
  1495.              number  is  reset  for  each range encountered.  The
  1496.              final sequence number in a range has the string 'E0'
  1497.              appended  to  it,  which  doesn't affect its numeric
  1498.              value, but gives you something to search for if  you
  1499.              want  to  exclude the endpoint.  You can exclude the
  1500.              beginning point by waiting for the  sequence  number
  1501.              to  be  greater than 1.  If either operand of scalar
  1502.              .. is static, that operand is implicitly compared to
  1503.              the $. variable, the current line number.  Examples:
  1504.  
  1505.              As a scalar operator:
  1506.                  if (101 .. 200) { print; }     # print 2nd hundred lines
  1507.  
  1508.                  next line if (1 .. /^$/); # skip header lines
  1509.  
  1510.                  s/^/> / if (/^$/ .. eof());    # quote body
  1511.  
  1512.  
  1513.  
  1514.  
  1515. Consensys Computer Inc.                                        23
  1516.  
  1517.  
  1518.  
  1519.  
  1520.  
  1521.  
  1522. PERL(1)                  USER COMMANDS                    PERL(1)
  1523.  
  1524.  
  1525.  
  1526.              As an array operator:
  1527.                  for (101 .. 200) { print; }    # print $_ 100 times
  1528.  
  1529.                  @foo = @foo[$[ .. $#foo]; # an expensive no-op
  1530.                  @foo = @foo[$#foo-4 .. $#foo]; # slice last 5 items
  1531.  
  1532.  
  1533.      -x      A file test.  This unary operator  takes  one  argu-
  1534.              ment,  either  a filename or a filehandle, and tests
  1535.              the associated file to  see  if  something  is  true
  1536.              about  it.   If  the  argument is omitted, tests $_,
  1537.              except for -t, which tests _S_T_D_I_N.  It returns 1  for
  1538.              true and '' for false, or the undefined value if the
  1539.              file doesn't exist.  Precedence is higher than logi-
  1540.              cal  and relational operators, but lower than arith-
  1541.              metic operators.  The operator may be any of:
  1542.                   -r   File is readable by effective uid.
  1543.                   -w   File is writable by effective uid.
  1544.                   -x   File is executable by effective uid.
  1545.                   -o   File is owned by effective uid.
  1546.                   -R   File is readable by real uid.
  1547.                   -W   File is writable by real uid.
  1548.                   -X   File is executable by real uid.
  1549.                   -O   File is owned by real uid.
  1550.                   -e   File exists.
  1551.                   -z   File has zero size.
  1552.                   -s   File has non-zero size (returns size).
  1553.                   -f   File is a plain file.
  1554.                   -d   File is a directory.
  1555.                   -l   File is a symbolic link.
  1556.                   -p   File is a named pipe (FIFO).
  1557.                   -S   File is a socket.
  1558.                   -b   File is a block special file.
  1559.                   -c   File is a character special file.
  1560.                   -u   File has setuid bit set.
  1561.                   -g   File has setgid bit set.
  1562.                   -k   File has sticky bit set.
  1563.                   -t   Filehandle is opened to a tty.
  1564.                   -T   File is a text file.
  1565.                   -B   File is a binary file (opposite of -T).
  1566.                   -M   Age of file in days when script started.
  1567.                   -A   Same for access time.
  1568.                   -C   Same for inode change time.
  1569.  
  1570.              The interpretation of the file permission  operators
  1571.              -r,  -R,  -w,  -W,  -x and -X is based solely on the
  1572.              mode of the file and the uids and gids of the  user.
  1573.              There  may be other reasons you can't actually read,
  1574.              write or execute the file.  Also note that, for  the
  1575.              superuser, -r, -R, -w and -W always return 1, and -x
  1576.              and -X return 1 if any execute bit  is  set  in  the
  1577.              mode.  Scripts run by the superuser may thus need to
  1578.  
  1579.  
  1580.  
  1581. Consensys Computer Inc.                                        24
  1582.  
  1583.  
  1584.  
  1585.  
  1586.  
  1587.  
  1588. PERL(1)                  USER COMMANDS                    PERL(1)
  1589.  
  1590.  
  1591.  
  1592.              do a stat() in order to determine the actual mode of
  1593.              the  file,  or  temporarily set the uid to something
  1594.              else.   (Note that several of  the  above  operators
  1595.              don't mean much under MS-DOS.)
  1596.  
  1597.              Example:
  1598.  
  1599.                   while (<>) {
  1600.                        chop;
  1601.                        next unless -f $_;  # ignore specials
  1602.                        ...
  1603.                   }
  1604.  
  1605.              Note that -s/a/b/ does not do  a  negated  substitu-
  1606.              tion.   Saying  -exp($foo)  still works as expected,
  1607.              however--only single letters following a  minus  are
  1608.              interpreted as file tests.
  1609.  
  1610.              The -T and -B switches work as follows.   The  first
  1611.              block  or so of the file is examined for odd charac-
  1612.              ters such as strange control  codes  or  metacharac-
  1613.              ters.   If too many odd characters (>10%) are found,
  1614.              it's a -B file, otherwise it's a -T file.  Also, any
  1615.              file  containing  null  in  the  first block is con-
  1616.              sidered a binary file.  If -T or -B  is  used  on  a
  1617.              filehandle,  the  current  stdio  buffer is examined
  1618.              rather than the first block.  Both -T and -B  return
  1619.              TRUE on a null file, or a file at EOF when testing a
  1620.              filehandle.
  1621.  
  1622.      If any of the file tests (or either stat operator) are given
  1623.      the  special  filehandle consisting of a solitary underline,
  1624.      then the stat structure of the previous file test  (or  stat
  1625.      operator) is used, saving a system call.  (This doesn't work
  1626.      with -t, and you need to remember that  lstat  and  -l  will
  1627.      leave  values  in  the stat structure for the symbolic link,
  1628.      not the real file.)  Example:
  1629.  
  1630.           print "Can do.\n" if -r $a || -w _ || -x _;
  1631.  
  1632.           stat($filename);
  1633.           print "Readable\n" if -r _;
  1634.           print "Writable\n" if -w _;
  1635.           print "Executable\n" if -x _;
  1636.           print "Setuid\n" if -u _;
  1637.           print "Setgid\n" if -g _;
  1638.           print "Sticky\n" if -k _;
  1639.           print "Text\n" if -T _;
  1640.           print "Binary\n" if -B _;
  1641.  
  1642.  
  1643.  
  1644.  
  1645.  
  1646.  
  1647. Consensys Computer Inc.                                        25
  1648.  
  1649.  
  1650.  
  1651.  
  1652.  
  1653.  
  1654. PERL(1)                  USER COMMANDS                    PERL(1)
  1655.  
  1656.  
  1657.  
  1658.      Here is what C has that _p_e_r_l doesn't:
  1659.  
  1660.      unary &     Address-of operator.
  1661.  
  1662.      unary *     Dereference-address operator.
  1663.  
  1664.      (TYPE)      Type casting operator.
  1665.  
  1666.      Like C, _p_e_r_l does a certain amount of expression  evaluation
  1667.      at  compile  time,  whenever  it  determines that all of the
  1668.      arguments to  an  operator  are  static  and  have  no  side
  1669.      effects.   In  particular,  string  concatenation happens at
  1670.      compile time between literals that don't do variable substi-
  1671.      tution.   Backslash  interpretation  also happens at compile
  1672.      time.  You can say
  1673.  
  1674.           'Now is the time for all' . "\n" .
  1675.           'good men to come to.'
  1676.  
  1677.      and this all reduces to one string internally.
  1678.  
  1679.      The autoincrement operator has a little extra built-in magic
  1680.      to it.  If you increment a variable that is numeric, or that
  1681.      has ever been used in a numeric context, you  get  a  normal
  1682.      increment.   If, however, the variable has only been used in
  1683.      string contexts since it was set, and has a  value  that  is
  1684.      not  null  and  matches the pattern /^[a-zA-Z]*[0-9]*$/, the
  1685.      increment is done as a  string,  preserving  each  character
  1686.      within its range, with carry:
  1687.  
  1688.           print ++($foo = '99');   # prints '100'
  1689.           print ++($foo = 'a0');   # prints 'a1'
  1690.           print ++($foo = 'Az');   # prints 'Ba'
  1691.           print ++($foo = 'zz');   # prints 'aaa'
  1692.  
  1693.      The autodecrement is not magical.
  1694.  
  1695.      The range operator (in an array context) makes  use  of  the
  1696.      magical  autoincrement  algorithm if the minimum and maximum
  1697.      are strings.  You can say
  1698.  
  1699.           @alphabet = ('A' .. 'Z');
  1700.  
  1701.      to get all the letters of the alphabet, or
  1702.  
  1703.           $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
  1704.  
  1705.      to get a hexadecimal digit, or
  1706.  
  1707.           @z2 = ('01' .. '31');  print @z2[$mday];
  1708.  
  1709.      to get dates  with  leading  zeros.   (If  the  final  value
  1710.  
  1711.  
  1712.  
  1713. Consensys Computer Inc.                                        26
  1714.  
  1715.  
  1716.  
  1717.  
  1718.  
  1719.  
  1720. PERL(1)                  USER COMMANDS                    PERL(1)
  1721.  
  1722.  
  1723.  
  1724.      specified  is not in the sequence that the magical increment
  1725.      would produce, the sequence goes until the next value  would
  1726.      be longer than the final value specified.)
  1727.  
  1728.      The || and && operators differ from C's in that, rather than
  1729.      returning  0  or  1,  they  return the last value evaluated.
  1730.      Thus, a portable way to find out the  home  directory  might
  1731.      be:
  1732.  
  1733.           $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
  1734.               (getpwuid($<))[7] || die "You're homeless!\n";
  1735.  
  1736.  
  1737.      Along with the literals and variables mentioned earlier, the
  1738.      operations in the following section can serve as terms in an
  1739.      expression.  Some of these operations  take  a  LIST  as  an
  1740.      argument.   Such  a  list  can consist of any combination of
  1741.      scalar arguments or array values; the array values  will  be
  1742.      included  in  the  list  as  if each individual element were
  1743.      interpolated at that point in the  list,  forming  a  longer
  1744.      single-dimensional array value.  Elements of the LIST should
  1745.      be separated by commas.  If an operation is listed both with
  1746.      and  without  parentheses around its arguments, it means you
  1747.      can either use it as a unary operator or as a function call.
  1748.      To  use  it  as  a function call, the next token on the same
  1749.      line must be a left parenthesis.  (There may be  intervening
  1750.      white  space.)  Such a function then has highest precedence,
  1751.      as you would expect from a function.   If  any  token  other
  1752.      than  a  left parenthesis follows, then it is a unary opera-
  1753.      tor, with a precedence depending only on  whether  it  is  a
  1754.      LIST  operator  or  not.   LIST  operators  have lowest pre-
  1755.      cedence.   All  other  unary  operators  have  a  precedence
  1756.      greater  than  relational operators but less than arithmetic
  1757.      operators.  See the section on Precedence.
  1758.  
  1759.      /PATTERN/
  1760.              See m/PATTERN/.
  1761.  
  1762.      ?PATTERN?
  1763.              This is just like the /pattern/ search, except  that
  1764.              it  matches  only  once  between  calls to the _r_e_s_e_t
  1765.              operator.  This is a useful  optimization  when  you
  1766.              only  want  to see the first occurrence of something
  1767.              in each file of a set of files, for instance.   Only
  1768.              ?? patterns local to the current package are reset.
  1769.  
  1770.      accept(NEWSOCKET,GENERICSOCKET)
  1771.              Does the same thing  that  the  accept  system  call
  1772.              does.   Returns  true  if it succeeded, false other-
  1773.              wise.  See example in section on  Interprocess  Com-
  1774.              munication.     Sockets are not yet supported on MS-
  1775.              DOS.
  1776.  
  1777.  
  1778.  
  1779. Consensys Computer Inc.                                        27
  1780.  
  1781.  
  1782.  
  1783.  
  1784.  
  1785.  
  1786. PERL(1)                  USER COMMANDS                    PERL(1)
  1787.  
  1788.  
  1789.  
  1790.      alarm(SECONDS)
  1791.  
  1792.      alarm SECONDS
  1793.              Arranges to have a SIGALRM delivered to this process
  1794.              after  the  specified  number  of  seconds (minus 1,
  1795.              actually) have elapsed.  Thus, alarm(15) will  cause
  1796.              a  SIGALRM at some point more than 14 seconds in the
  1797.              future.  Only one timer may  be  counting  at  once.
  1798.              Each  call disables the previous timer, and an argu-
  1799.              ment of 0 may be supplied  to  cancel  the  previous
  1800.              timer  without  starting  a  new  one.  The returned
  1801.              value is the amount of time remaining on the  previ-
  1802.              ous timer.   Not supported on MS-DOS.
  1803.  
  1804.      atan2(Y,X)
  1805.              Returns the arctangent of Y/X in the  range  -PI  to
  1806.              PI.
  1807.  
  1808.      bind(SOCKET,NAME)
  1809.              Does the same thing that the bind system call  does.
  1810.              Returns true if it succeeded, false otherwise.  NAME
  1811.              should be a packed address of the  proper  type  for
  1812.              the  socket.  See example in section on Interprocess
  1813.              Communication.   Sockets are not  yet  supported  on
  1814.              MS-DOS.
  1815.  
  1816.      binmode(FILEHANDLE)
  1817.  
  1818.      binmode FILEHANDLE
  1819.              Arranges for the file to be read in "binary" mode in
  1820.              operating  systems, such as MS-DOS, that distinguish
  1821.              between binary and text files.  Files that  are  not
  1822.              read  in binary mode have CR LF sequences translated
  1823.              to LF on input and LF translated to CR LF on output.
  1824.              In addition, MS-DOS will consider ^Z to indicate end
  1825.              of file for files being read in text mode. The is no
  1826.              way  to  return a file handle to text mode.  Binmode
  1827.              has no effect  under  Unix.   If  FILEHANDLE  is  an
  1828.              expression,  the  value  is taken as the name of the
  1829.              filehandle.
  1830.  
  1831.      caller(EXPR)
  1832.  
  1833.      caller  Returns the context of the current subroutine call:
  1834.  
  1835.                   ($package,$filename,$line) = caller;
  1836.  
  1837.              With EXPR, returns some extra information  that  the
  1838.              debugger  uses to print a stack trace.  The value of
  1839.              EXPR indicates how  many  call  frames  to  go  back
  1840.              before the current one.
  1841.  
  1842.  
  1843.  
  1844.  
  1845. Consensys Computer Inc.                                        28
  1846.  
  1847.  
  1848.  
  1849.  
  1850.  
  1851.  
  1852. PERL(1)                  USER COMMANDS                    PERL(1)
  1853.  
  1854.  
  1855.  
  1856.      chdir(EXPR)
  1857.  
  1858.      chdir EXPR
  1859.              Changes the working directory to EXPR, if  possible.
  1860.              If  EXPR  is  omitted,  changes  to  home directory.
  1861.              Returns 1 upon success, 0  otherwise.   See  example
  1862.              under _d_i_e.
  1863.  
  1864.              On MS-DOS, the path  and/or  the  directory  can  be
  1865.              specified.
  1866.  
  1867.              chdir "c:/junk/subdir";
  1868.              chdir "e:";
  1869.              chdir "abc/xyz";
  1870.  
  1871.              The first of these changes  the  default  drive  and
  1872.              directory.  The second changes to the default direc-
  1873.              tory on drive E:.  The third changes  the  directory
  1874.              on  the  current drive.  As with all filenames, for-
  1875.              ward slashes are recommended inside _p_e_r_l.  (See  the
  1876.              section on MS-DOS considerations.)
  1877.  
  1878.      chmod(LIST)
  1879.  
  1880.      chmod LIST
  1881.              Changes the permissions of a  list  of  files.   The
  1882.              first  element  of  the  list  must be the numerical
  1883.              mode.  Returns  the  number  of  files  successfully
  1884.              changed.
  1885.  
  1886.                   $cnt = chmod 0755, 'foo', 'bar';
  1887.                   chmod 0755, @executables;
  1888.  
  1889.  
  1890.      chop(LIST)
  1891.  
  1892.      chop(VARIABLE)
  1893.  
  1894.      chop VARIABLE
  1895.  
  1896.      chop    Chops off the last character of a string and returns
  1897.              the  character  chopped.   It's  used  primarily  to
  1898.              remove the newline from the end of an input  record,
  1899.              but  is  much  more efficient than s/\n// because it
  1900.              neither scans nor copies the string.  If VARIABLE is
  1901.              omitted, chops $_.  Example:
  1902.  
  1903.                   while (<>) {
  1904.                        chop;     # avoid \n on last field
  1905.                        @array = split(/:/);
  1906.                        ...
  1907.                   }
  1908.  
  1909.  
  1910.  
  1911. Consensys Computer Inc.                                        29
  1912.  
  1913.  
  1914.  
  1915.  
  1916.  
  1917.  
  1918. PERL(1)                  USER COMMANDS                    PERL(1)
  1919.  
  1920.  
  1921.  
  1922.              You can actually chop  anything  that's  an  lvalue,
  1923.              including an assignment:
  1924.  
  1925.                   chop($cwd = `pwd`);
  1926.                   chop($answer = <STDIN>);
  1927.  
  1928.              If you chop a list, each element is  chopped.   Only
  1929.              the value of the last chop is returned.
  1930.  
  1931.      chown(LIST)
  1932.  
  1933.      chown LIST
  1934.              Changes the owner (and group) of a  list  of  files.
  1935.              The  first  two  elements  of  the  list must be the
  1936.              NUMERICAL uid and gid, in that order.   Returns  the
  1937.              number of files successfully changed.  Not supported
  1938.              on MS-DOS.
  1939.  
  1940.                   $cnt = chown $uid, $gid, 'foo', 'bar';
  1941.                   chown $uid, $gid, @filenames;
  1942.  
  1943.              Here's an example that looks up non-numeric uids  in
  1944.              the passwd file:
  1945.  
  1946.                   print "User: ";
  1947.                   $user = <STDIN>;
  1948.                   chop($user);
  1949.                   print "Files: "
  1950.                   $pattern = <STDIN>;
  1951.                   chop($pattern);
  1952.                   open(pass, '/etc/passwd')
  1953.                        || die "Can't open passwd: $!\n";
  1954.                   while (<pass>) {
  1955.                        ($login,$pass,$uid,$gid) = split(/:/);
  1956.                        $uid{$login} = $uid;
  1957.                        $gid{$login} = $gid;
  1958.                   }
  1959.                   @ary = <${pattern}>;     # get filenames
  1960.                   if ($uid{$user} eq '') {
  1961.                        die "$user not in passwd file";
  1962.                   }
  1963.                   else {
  1964.                        chown $uid{$user}, $gid{$user}, @ary;
  1965.                   }
  1966.  
  1967.  
  1968.      chroot(FILENAME)
  1969.  
  1970.      chroot FILENAME
  1971.              Does the same as the system call of that  name.   If
  1972.              you  don't  know what it does, don't worry about it.
  1973.              If FILENAME is omitted, does chroot  to  $_.     Not
  1974.  
  1975.  
  1976.  
  1977. Consensys Computer Inc.                                        30
  1978.  
  1979.  
  1980.  
  1981.  
  1982.  
  1983.  
  1984. PERL(1)                  USER COMMANDS                    PERL(1)
  1985.  
  1986.  
  1987.  
  1988.              supported on MS-DOS.
  1989.  
  1990.      close(FILEHANDLE)
  1991.  
  1992.      close FILEHANDLE
  1993.              Closes the file or pipe  associated  with  the  file
  1994.              handle.   You  don't have to close FILEHANDLE if you
  1995.              are immediately going to  do  another  open  on  it,
  1996.              since open will close it for you.  (See _o_p_e_n.)  How-
  1997.              ever, an explicit close on an input file resets  the
  1998.              line  counter ($.), while the implicit close done by
  1999.              _o_p_e_n does not.  Also, closing a pipe will  wait  for
  2000.              the  process  executing  on the pipe to complete, in
  2001.              case you want to look at  the  output  of  the  pipe
  2002.              afterwards.  Closing a pipe explicitly also puts the
  2003.              status value of the command into $?.  Example:
  2004.  
  2005.                   open(OUTPUT, '|sort >foo');   # pipe to sort
  2006.                   ...  # print stuff to output
  2007.                   close OUTPUT;       # wait for sort to finish
  2008.                   open(INPUT, 'foo'); # get sort's results
  2009.  
  2010.              FILEHANDLE may be an expression  whose  value  gives
  2011.              the real filehandle name.
  2012.  
  2013.      closedir(DIRHANDLE)
  2014.  
  2015.      closedir DIRHANDLE
  2016.              Closes a directory opened by opendir().
  2017.  
  2018.      connect(SOCKET,NAME)
  2019.              Does the same thing that  the  connect  system  call
  2020.              does.   Returns  true  if it succeeded, false other-
  2021.              wise.  NAME should  be  a  package  address  of  the
  2022.              proper  type for the socket.  See example in section
  2023.              on Interprocess Communication.   Sockets are not yet
  2024.              supported on MS-DOS.
  2025.  
  2026.      cos(EXPR)
  2027.  
  2028.      cos EXPR
  2029.              Returns the cosine of EXPR (expressed  in  radians).
  2030.              If EXPR is omitted takes cosine of $_.
  2031.  
  2032.      crypt(PLAINTEXT,SALT)
  2033.              Encrypts a string exactly like the crypt()  function
  2034.              in  the C library.  Useful for checking the password
  2035.              file for lousy passwords.   Only  the  guys  wearing
  2036.              white  hats  should  do this.   Not supported on MS-
  2037.              DOS.
  2038.  
  2039.  
  2040.  
  2041.  
  2042.  
  2043. Consensys Computer Inc.                                        31
  2044.  
  2045.  
  2046.  
  2047.  
  2048.  
  2049.  
  2050. PERL(1)                  USER COMMANDS                    PERL(1)
  2051.  
  2052.  
  2053.  
  2054.      dbmclose(ASSOC_ARRAY)
  2055.  
  2056.      dbmclose ASSOC_ARRAY
  2057.              Breaks the binding between a dbm file and an associ-
  2058.              ative  array.   The values remaining in the associa-
  2059.              tive array are meaningless unless you happen to want
  2060.              to  know  what  was  in  the cache for the dbm file.
  2061.              This function is only useful if you have ndbm.
  2062.  
  2063.      dbmopen(ASSOC,DBNAME,MODE)
  2064.              This binds a dbm or  ndbm  file  to  an  associative
  2065.              array.   ASSOC is the name of the associative array.
  2066.              (Unlike normal open, the first  argument  is  NOT  a
  2067.              filehandle,  even though it looks like one).  DBNAME
  2068.              is the name of the database  (without  the  .dir  or
  2069.              .pag extension).  If the database does not exist, it
  2070.              is created with protection  specified  by  MODE  (as
  2071.              modified  by  the  umask).  If your system only sup-
  2072.              ports the older dbm functions, you may perform  only
  2073.              one  dbmopen  in  your  program.  If your system has
  2074.              neither dbm nor ndbm,  calling  dbmopen  produces  a
  2075.              fatal  error.   (MS-DOS  users: the MS-DOS port uses
  2076.              Gnu-dbm, which supports multiple files.)
  2077.  
  2078.              Values assigned to the associative  array  prior  to
  2079.              the  dbmopen  are  lost.  A certain number of values
  2080.              from the dbm file are cached in memory.  By  default
  2081.              this number is 64, but you can increase it by preal-
  2082.              locating that number of garbage entries in the asso-
  2083.              ciative array before the dbmopen.  You can flush the
  2084.              cache if necessary with the reset command.
  2085.  
  2086.              If you don't have write access to the dbm file,  you
  2087.              can  only  read associative array variables, not set
  2088.              them.  If you want to test whether  you  can  write,
  2089.              either  use  file tests or try setting a dummy array
  2090.              entry inside an eval, which will trap the error.
  2091.  
  2092.              Note that functions such as keys() and values()  may
  2093.              return  huge  array  values  when  used on large dbm
  2094.              files.  You may prefer to use the each() function to
  2095.              iterate over large dbm files.  Example:
  2096.  
  2097.                   # print out history file offsets
  2098.                   dbmopen(HIST,'/usr/lib/news/history',0666);
  2099.                   while (($key,$val) = each %HIST) {
  2100.                        print $key, ' = ', unpack('L',$val), "\n";
  2101.                   }
  2102.                   dbmclose(HIST);
  2103.  
  2104.  
  2105.  
  2106.  
  2107.  
  2108.  
  2109. Consensys Computer Inc.                                        32
  2110.  
  2111.  
  2112.  
  2113.  
  2114.  
  2115.  
  2116. PERL(1)                  USER COMMANDS                    PERL(1)
  2117.  
  2118.  
  2119.  
  2120.      defined(EXPR)
  2121.  
  2122.      defined EXPR
  2123.              Returns a boolean value saying  whether  the  lvalue
  2124.              EXPR  has  a  real  value  or  not.  Many operations
  2125.              return the undefined value under exceptional  condi-
  2126.              tions,  such as end of file, uninitialized variable,
  2127.              system error and such.  This function allows you  to
  2128.              distinguish  between  an undefined null string and a
  2129.              defined  null  string  with  operations  that  might
  2130.              return a real null string, in particular referencing
  2131.              elements of an array.  You may also check to see  if
  2132.              arrays  or  subroutines  exist.   Use  on predefined
  2133.              variables is not  guaranteed  to  produce  intuitive
  2134.              results.  Examples:
  2135.  
  2136.                   print if defined $switch{'D'};
  2137.                   print "$val\n" while defined($val = pop(@ary));
  2138.                   die "Can't readlink $sym: $!"
  2139.                        unless defined($value = readlink $sym);
  2140.                   eval '@foo = ()' if defined(@foo);
  2141.                   die "No XYZ package defined" unless defined %_XYZ;
  2142.                   sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }
  2143.  
  2144.              See also undef.
  2145.  
  2146.      delete $ASSOC{KEY}
  2147.              Deletes the specified value from the specified asso-
  2148.              ciative  array.   Returns  the deleted value, or the
  2149.              undefined value if nothing  was  deleted.   Deleting
  2150.              from $ENV{} modifies the environment.  Deleting from
  2151.              an array bound to a dbm file deletes the entry  from
  2152.              the dbm file.
  2153.  
  2154.              The following deletes all the values of an  associa-
  2155.              tive array:
  2156.  
  2157.                   foreach $key (keys %ARRAY) {
  2158.                        delete $ARRAY{$key};
  2159.                   }
  2160.  
  2161.              (But it would be faster to use  the  _r_e_s_e_t  command.
  2162.              Saying undef %ARRAY is faster yet.)
  2163.  
  2164.      die(LIST)
  2165.  
  2166.      die LIST
  2167.              Outside of an eval, prints  the  value  of  LIST  to
  2168.              _S_T_D_E_R_R  and  exits  with  the  current  value  of $!
  2169.              (errno).  If $! is 0, exits with the value of ($? >>
  2170.              8)  (`command`  status).   If  ($? >> 8) is 0, exits
  2171.              with 255.  Inside an  eval,  the  error  message  is
  2172.  
  2173.  
  2174.  
  2175. Consensys Computer Inc.                                        33
  2176.  
  2177.  
  2178.  
  2179.  
  2180.  
  2181.  
  2182. PERL(1)                  USER COMMANDS                    PERL(1)
  2183.  
  2184.  
  2185.  
  2186.              stuffed  into $@ and the eval is terminated with the
  2187.              undefined value.
  2188.  
  2189.              Equivalent examples:
  2190.  
  2191.                   die "Can't cd to spool: $!\n"
  2192.                        unless chdir '/usr/spool/news';
  2193.  
  2194.                   chdir '/usr/spool/news' || die "Can't cd to spool: $!\n"
  2195.  
  2196.  
  2197.              If the value of EXPR does not end in a newline,  the
  2198.              current script line number and input line number (if
  2199.              any) are also printed, and a  newline  is  supplied.
  2200.              Hint:  sometimes  appending ", stopped" to your mes-
  2201.              sage will cause it to make  better  sense  when  the
  2202.              string  "at  foo line 123" is appended.  Suppose you
  2203.              are running script "canasta".
  2204.  
  2205.                   die "/etc/games is no good";
  2206.                   die "/etc/games is no good, stopped";
  2207.  
  2208.              produce, respectively
  2209.  
  2210.                   /etc/games is no good at canasta line 123.
  2211.                   /etc/games is no good, stopped at canasta line 123.
  2212.  
  2213.              See also _e_x_i_t.
  2214.  
  2215.      do BLOCK
  2216.              Returns  the  value  of  the  last  command  in  the
  2217.              sequence of commands indicated by BLOCK.  When modi-
  2218.              fied by a loop modifier,  executes  the  BLOCK  once
  2219.              before testing the loop condition.  (On other state-
  2220.              ments  the  loop  modifiers  test  the   conditional
  2221.              first.)
  2222.  
  2223.      do SUBROUTINE (LIST)
  2224.              Executes a SUBROUTINE declared by a _s_u_b declaration,
  2225.              and   returns  the  value  of  the  last  expression
  2226.              evaluated in SUBROUTINE.  If there is no  subroutine
  2227.              by  that name, produces a fatal error.  (You may use
  2228.              the "defined" operator to determine if a  subroutine
  2229.              exists.)  If you pass arrays as part of LIST you may
  2230.              wish to pass the length of the  array  in  front  of
  2231.              each  array.   (See the section on subroutines later
  2232.              on.)  The parentheses are required to  avoid  confu-
  2233.              sion with the "do EXPR" form.
  2234.  
  2235.              SUBROUTINE may also be a single scalar variable,  in
  2236.              which  case the name of the subroutine to execute is
  2237.              taken from the variable.
  2238.  
  2239.  
  2240.  
  2241. Consensys Computer Inc.                                        34
  2242.  
  2243.  
  2244.  
  2245.  
  2246.  
  2247.  
  2248. PERL(1)                  USER COMMANDS                    PERL(1)
  2249.  
  2250.  
  2251.  
  2252.              As an alternate (and preferred) form, you may call a
  2253.              subroutine  by prefixing the name with an ampersand:
  2254.              &foo(@args).  If you aren't passing  any  arguments,
  2255.              you  don't have to use parentheses.  If you omit the
  2256.              parentheses, no @_ array is passed  to  the  subrou-
  2257.              tine.   The  &  form is also used to specify subrou-
  2258.              tines to the defined and undef operators:
  2259.  
  2260.                   if (defined &$var) { &$var($parm); undef &$var; }
  2261.  
  2262.  
  2263.      do EXPR Uses the value of EXPR as a  filename  and  executes
  2264.              the contents of the file as a _p_e_r_l script.  Its pri-
  2265.              mary use is to include subroutines from a _p_e_r_l  sub-
  2266.              routine library.
  2267.  
  2268.                   do 'stat.pl';
  2269.  
  2270.              is just like
  2271.  
  2272.                   eval `cat stat.pl`;
  2273.  
  2274.              except that it's more efficient, more concise, keeps
  2275.              track  of  the  current filename for error messages,
  2276.              and searches all the ----IIII libraries if the file  isn't
  2277.              in the current directory (see also the @INC array in
  2278.              Predefined Names).  It's the same, however, in  that
  2279.              it  does reparse the file every time you call it, so
  2280.              if you are going to use the file inside a  loop  you
  2281.              might  prefer to use -P and #include, at the expense
  2282.              of a little more startup time.   (The  main  problem
  2283.              with #include is that cpp doesn't grok # comments--a
  2284.              workaround is to use ";#" for standalone  comments.)
  2285.              Note that the following are NOT equivalent:
  2286.  
  2287.                   do $foo;  # eval a file
  2288.                   do $foo();     # call a subroutine
  2289.  
  2290.              Note that inclusion of library  routines  is  better
  2291.              done with the "require" operator.
  2292.  
  2293.      dump LABEL
  2294.              This causes an immediate core dump.  Primarily  this
  2295.              is  so  that  you can use the undump program to turn
  2296.              your core dump into an executable binary after  hav-
  2297.              ing  initialized all your variables at the beginning
  2298.              of the program.  When the new binary is executed  it
  2299.              will begin by executing a "goto LABEL" (with all the
  2300.              restrictions that goto suffers).  Think of it  as  a
  2301.              goto  with  an  intervening core dump and reincarna-
  2302.              tion.  If LABEL is  omitted,  restarts  the  program
  2303.              from the top.  WARNING: any files opened at the time
  2304.  
  2305.  
  2306.  
  2307. Consensys Computer Inc.                                        35
  2308.  
  2309.  
  2310.  
  2311.  
  2312.  
  2313.  
  2314. PERL(1)                  USER COMMANDS                    PERL(1)
  2315.  
  2316.  
  2317.  
  2318.              of the dump will NOT be open any more when the  pro-
  2319.              gram is reincarnated, with possible resulting confu-
  2320.              sion on the part of perl.  See also -u.    Not  sup-
  2321.              ported on MS-DOS.
  2322.  
  2323.              Example:
  2324.  
  2325.                   #!/usr/bin/perl
  2326.                   require 'getopt.pl';
  2327.                   require 'stat.pl';
  2328.                   %days = (
  2329.                       'Sun',1,
  2330.                       'Mon',2,
  2331.                       'Tue',3,
  2332.                       'Wed',4,
  2333.                       'Thu',5,
  2334.                       'Fri',6,
  2335.                       'Sat',7);
  2336.  
  2337.                   dump QUICKSTART if $ARGV[0] eq '-d';
  2338.  
  2339.                  QUICKSTART:
  2340.                   do Getopt('f');
  2341.  
  2342.  
  2343.      each(ASSOC_ARRAY)
  2344.  
  2345.      each ASSOC_ARRAY
  2346.              Returns a 2 element array consisting of the key  and
  2347.              value for the next value of an associative array, so
  2348.              that you can iterate over it.  Entries are  returned
  2349.              in  an  apparently  random order.  When the array is
  2350.              entirely read, a null array is returned (which  when
  2351.              assigned produces a FALSE (0) value).  The next call
  2352.              to each() after that  will  start  iterating  again.
  2353.              The  iterator  can  be reset only by reading all the
  2354.              elements from the array.  You must  not  modify  the
  2355.              array  while  iterating  over it.  There is a single
  2356.              iterator for each associative array, shared  by  all
  2357.              each(),  keys()  and  values() function calls in the
  2358.              program.  The following prints out your  environment
  2359.              like  the  printenv  program,  only  in  a different
  2360.              order:
  2361.  
  2362.                   while (($key,$value) = each %ENV) {
  2363.                        print "$key=$value\n";
  2364.                   }
  2365.  
  2366.              See also keys() and values().
  2367.  
  2368.  
  2369.  
  2370.  
  2371.  
  2372.  
  2373. Consensys Computer Inc.                                        36
  2374.  
  2375.  
  2376.  
  2377.  
  2378.  
  2379.  
  2380. PERL(1)                  USER COMMANDS                    PERL(1)
  2381.  
  2382.  
  2383.  
  2384.      eof(FILEHANDLE)
  2385.  
  2386.      eof()
  2387.  
  2388.      eof     Returns 1 if the next read on FILEHANDLE will return
  2389.              end of file, or if FILEHANDLE is not open.  FILEHAN-
  2390.              DLE may be an expression whose value gives the  real
  2391.              filehandle  name.  (Note that this function actually
  2392.              reads a character and then ungetc's it, so it is not
  2393.              very  useful  in  an  interactive  context.)  An eof
  2394.              without an argument returns the eof status  for  the
  2395.              last file read.  Empty parentheses () may be used to
  2396.              indicate the pseudo file formed of the files  listed
  2397.              on the command line, i.e. eof() is reasonable to use
  2398.              inside a while (<>) loop to detect the end  of  only
  2399.              the  last  file.   Use  eof(ARGV) or eof without the
  2400.              parentheses to test EACH file in a while (<>)  loop.
  2401.              Examples:
  2402.  
  2403.                   # insert dashes just before last line of last file
  2404.                   while (<>) {
  2405.                        if (eof()) {
  2406.                             print "--------------\n";
  2407.                        }
  2408.                        print;
  2409.                   }
  2410.  
  2411.                   # reset line numbering on each input file
  2412.                   while (<>) {
  2413.                        print "$.\t$_";
  2414.                        if (eof) {     # Not eof().
  2415.                             close(ARGV);
  2416.                        }
  2417.                   }
  2418.  
  2419.  
  2420.      eval(EXPR)
  2421.  
  2422.      eval EXPR
  2423.  
  2424.      eval BLOCK
  2425.              EXPR is parsed and executed as if it were  a  little
  2426.              _p_e_r_l  program.  It is executed in the context of the
  2427.              current _p_e_r_l program, so that any variable settings,
  2428.              subroutine  or format definitions remain afterwards.
  2429.              The value returned is the value of the last  expres-
  2430.              sion  evaluated, just as with subroutines.  If there
  2431.              is a syntax error or runtime error, or a die  state-
  2432.              ment  is executed, an undefined value is returned by
  2433.              eval, and $@ is set to the error message.  If  there
  2434.              was  no error, $@ is guaranteed to be a null string.
  2435.              If  EXPR  is  omitted,  evaluates  $_.   The   final
  2436.  
  2437.  
  2438.  
  2439. Consensys Computer Inc.                                        37
  2440.  
  2441.  
  2442.  
  2443.  
  2444.  
  2445.  
  2446. PERL(1)                  USER COMMANDS                    PERL(1)
  2447.  
  2448.  
  2449.  
  2450.              semicolon,  if  any, may be omitted from the expres-
  2451.              sion.
  2452.  
  2453.              Note that, since eval traps otherwise-fatal  errors,
  2454.              it  is  useful  for determining whether a particular
  2455.              feature (such as dbmopen or symlink) is implemented.
  2456.              It  is  also  Perl's  exception  trapping mechanism,
  2457.              where the die operator is used to raise exceptions.
  2458.  
  2459.              If the code to be executed doesn't vary, you may use
  2460.              the  eval-BLOCK form to trap run-time errors without
  2461.              incurring the penalty of recompiling each time.  The
  2462.              error,  if any, is still returned in $@.  Evaluating
  2463.              a  single-quoted  string  (as  EXPR)  has  the  same
  2464.              effect,  except that the eval-EXPR form reports syn-
  2465.              tax errors at run time via  $@,  whereas  the  eval-
  2466.              BLOCK  form  reports  syntax errors at compile time.
  2467.              The eval-EXPR form is optimized  to  eval-BLOCK  the
  2468.              first time it succeeds.  (Since the replacement side
  2469.              of a  substitution  is  considered  a  single-quoted
  2470.              string when you use the e modifier, the same optimi-
  2471.              zation occurs there.)  Examples:
  2472.  
  2473.                   # make divide-by-zero non-fatal
  2474.                   eval { $answer = $a / $b; }; warn $@ if $@;
  2475.  
  2476.                   # optimized to same thing after first use
  2477.                   eval '$answer = $a / $b'; warn $@ if $@;
  2478.  
  2479.                   # a compile-time error
  2480.                   eval { $answer = };
  2481.  
  2482.                   # a run-time error
  2483.                   eval '$answer =';   # sets $@
  2484.  
  2485.  
  2486.      exec(LIST)
  2487.  
  2488.      exec LIST
  2489.              If there is more than one argument in  LIST,  or  if
  2490.              LIST  is  an  array  with more than one value, calls
  2491.              execvp() with the arguments in LIST.   If  there  is
  2492.              only  one  scalar  argument, the argument is checked
  2493.              for shell metacharacters.  If  there  are  any,  the
  2494.              entire  argument is passed to "/bin/sh -c" for pars-
  2495.              ing.  If there are none, the argument is split  into
  2496.              words and passed directly to execvp(), which is more
  2497.              efficient.  Note: exec (and  system)  do  not  flush
  2498.              your  output  buffer,  so  you may need to set $| to
  2499.              avoid lost output.  Examples:
  2500.  
  2501.                   exec '/bin/echo', 'Your arguments are: ', @ARGV;
  2502.  
  2503.  
  2504.  
  2505. Consensys Computer Inc.                                        38
  2506.  
  2507.  
  2508.  
  2509.  
  2510.  
  2511.  
  2512. PERL(1)                  USER COMMANDS                    PERL(1)
  2513.  
  2514.  
  2515.  
  2516.                   exec "sort $outfile | uniq";
  2517.  
  2518.  
  2519.              If you don't really want to execute the first  argu-
  2520.              ment, but want to lie to the program you are execut-
  2521.              ing about its own name, you can specify the  program
  2522.              you  actually  want  to  run  by assigning that to a
  2523.              variable and putting the name  of  the  variable  in
  2524.              front  of  the  LIST  without a comma.  (This always
  2525.              forces interpretation of the LIST as a  multi-valued
  2526.              list,  even  if there is only a single scalar in the
  2527.              list.)  Example:
  2528.  
  2529.                   $shell = '/bin/csh';
  2530.                   exec $shell '-sh';       # pretend it's a login shell
  2531.  
  2532.              The MS-DOS  implementation  of  _e_x_e_c  has  problems.
  2533.              Unlike _s_y_s_t_e_m and pipes it is not MKS toolkit compa-
  2534.              tible.  As of this writing (September 1991) it  will
  2535.              not  even allow for temporary file cleanup.  The use
  2536.              of _e_x_e_c on MS-DOS is strongly discouraged.
  2537.  
  2538.      exit(EXPR)
  2539.  
  2540.      exit EXPR
  2541.              Evaluates  EXPR  and  exits  immediately  with  that
  2542.              value.  Example:
  2543.  
  2544.                   $ans = <STDIN>;
  2545.                   exit 0 if $ans =~ /^[Xx]/;
  2546.  
  2547.              See also _d_i_e.  If EXPR  is  omitted,  exits  with  0
  2548.              status.
  2549.  
  2550.      exp(EXPR)
  2551.  
  2552.      exp EXPR
  2553.              Returns _e to the power of EXPR.  If EXPR is omitted,
  2554.              gives exp($_).
  2555.  
  2556.      fcntl(FILEHANDLE,FUNCTION,SCALAR)
  2557.              Implements the fcntl(2) function.   You'll  probably
  2558.              have to say
  2559.  
  2560.                   require "fcntl.ph"; # probably /usr/local/lib/perl/fcntl.ph
  2561.  
  2562.              first to get the correct function  definitions.   If
  2563.              fcntl.ph  doesn't  exist or doesn't have the correct
  2564.              definitions you'll have to roll your own,  based  on
  2565.              your  C  header files such as <sys/fcntl.h>.  (There
  2566.              is a perl script called h2ph  that  comes  with  the
  2567.              perl  kit  which  may  help  you in this.)  Argument
  2568.  
  2569.  
  2570.  
  2571. Consensys Computer Inc.                                        39
  2572.  
  2573.  
  2574.  
  2575.  
  2576.  
  2577.  
  2578. PERL(1)                  USER COMMANDS                    PERL(1)
  2579.  
  2580.  
  2581.  
  2582.              processing and value return works  just  like  ioctl
  2583.              below.   Note  that fcntl will produce a fatal error
  2584.              if  used  on  a  machine  that   doesn't   implement
  2585.              fcntl(2).   Not supported on MS-DOS.
  2586.  
  2587.      fileno(FILEHANDLE)
  2588.  
  2589.      fileno FILEHANDLE
  2590.              Returns the file descriptor for a filehandle.   Use-
  2591.              ful  for  constructing  bitmaps  for  select().   If
  2592.              FILEHANDLE is an expression, the value is  taken  as
  2593.              the name of the filehandle.
  2594.  
  2595.      flock(FILEHANDLE,OPERATION)
  2596.              Calls flock(2) on FILEHANDLE.   See manual page  for
  2597.              flock(2)  for definition of OPERATION.  Returns true
  2598.              for success, false on failure.  Will produce a fatal
  2599.              error  if  used  on a machine that doesn't implement
  2600.              flock(2).  Here's a mailbox appender  for  BSD  sys-
  2601.              tems.
  2602.  
  2603.                   $LOCK_SH = 1;
  2604.                   $LOCK_EX = 2;
  2605.                   $LOCK_NB = 4;
  2606.                   $LOCK_UN = 8;
  2607.  
  2608.                   sub lock {
  2609.                       flock(MBOX,$LOCK_EX);
  2610.                       # and, in case someone appended
  2611.                       # while we were waiting...
  2612.                       seek(MBOX, 0, 2);
  2613.                   }
  2614.  
  2615.                   sub unlock {
  2616.                       flock(MBOX,$LOCK_UN);
  2617.                   }
  2618.  
  2619.                   open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
  2620.                        || die "Can't open mailbox: $!";
  2621.  
  2622.                   do lock();
  2623.                   print MBOX $msg,"\n\n";
  2624.                   do unlock();
  2625.  
  2626.  
  2627.              File locking is  not  supported  on  MS-DOS,  though
  2628.              perhaps  it  could  be constructed using MS-DOS file
  2629.              constructions.)
  2630.  
  2631.      fork    Does a fork() call.  Returns the child  pid  to  the
  2632.              parent  process  and  0 to the child process.  Note:
  2633.              unflushed   buffers   remain   unflushed   in   both
  2634.  
  2635.  
  2636.  
  2637. Consensys Computer Inc.                                        40
  2638.  
  2639.  
  2640.  
  2641.  
  2642.  
  2643.  
  2644. PERL(1)                  USER COMMANDS                    PERL(1)
  2645.  
  2646.  
  2647.  
  2648.              processes,  which  means  you  may need to set $| to
  2649.              avoid duplicate output.   Not supported on MS-DOS.
  2650.  
  2651.      getc(FILEHANDLE)
  2652.  
  2653.      getc FILEHANDLE
  2654.  
  2655.      getc    Returns the  next  character  from  the  input  file
  2656.              attached to FILEHANDLE, or a null string at EOF.  If
  2657.              FILEHANDLE is omitted, reads from STDIN.
  2658.  
  2659.      getlogin
  2660.              Returns the current login from  /etc/utmp,  if  any.
  2661.              If  null,  use getpwuid.  (Not supported on MS-DOS.)
  2662.                   $login  =  getlogin  ||  (getpwuid($<))[0]   ||
  2663.              "Somebody";
  2664.  
  2665.      getpeername(SOCKET)
  2666.              Returns the packed sockaddr address of other end  of
  2667.              the  SOCKET  connection.   (Sockets are not yet sup-
  2668.              ported on MS-DOS.)
  2669.  
  2670.                   # An internet sockaddr
  2671.                   $sockaddr = 'S n a4 x8';
  2672.                   $hersockaddr = getpeername(S);
  2673.                   ($family, $port, $heraddr) =
  2674.                             unpack($sockaddr,$hersockaddr);
  2675.  
  2676.  
  2677.      getpgrp(PID)
  2678.  
  2679.      getpgrp PID
  2680.              Returns the current process group for the  specified
  2681.              PID,  0  for  the  current  process.  Will produce a
  2682.              fatal error if used on a machine that doesn't imple-
  2683.              ment  getpgrp(2).   If EXPR is omitted, returns pro-
  2684.              cess group of current process.    Not  supported  on
  2685.              MS-DOS.
  2686.  
  2687.      getppid On Unix, returns the process id of the  parent  pro-
  2688.              cess.  Not supported on MS-DOS.
  2689.  
  2690.      getpriority(WHICH,WHO)
  2691.              Returns the current priority for a process,  a  pro-
  2692.              cess  group, or a user.  (See getpriority(2).)  Will
  2693.              produce a fatal error if  used  on  a  machine  that
  2694.              doesn't implement getpriority(2).   Not supported on
  2695.              MS-DOS.
  2696.  
  2697.      getpwnam(NAME)
  2698.  
  2699.  
  2700.  
  2701.  
  2702.  
  2703. Consensys Computer Inc.                                        41
  2704.  
  2705.  
  2706.  
  2707.  
  2708.  
  2709.  
  2710. PERL(1)                  USER COMMANDS                    PERL(1)
  2711.  
  2712.  
  2713.  
  2714.      getgrnam(NAME)
  2715.  
  2716.      gethostbyname(NAME)
  2717.  
  2718.      getnetbyname(NAME)
  2719.  
  2720.      getprotobyname(NAME)
  2721.  
  2722.      getpwuid(UID)
  2723.  
  2724.      getgrgid(GID)
  2725.  
  2726.      getservbyname(NAME,PROTO)
  2727.  
  2728.      gethostbyaddr(ADDR,ADDRTYPE)
  2729.  
  2730.      getnetbyaddr(ADDR,ADDRTYPE)
  2731.  
  2732.      getprotobynumber(NUMBER)
  2733.  
  2734.      getservbyport(PORT,PROTO)
  2735.  
  2736.      getpwent
  2737.  
  2738.      getgrent
  2739.  
  2740.      gethostent
  2741.  
  2742.      getnetent
  2743.  
  2744.      getprotoent
  2745.  
  2746.      getservent
  2747.  
  2748.      setpwent
  2749.  
  2750.      setgrent
  2751.  
  2752.      sethostent(STAYOPEN)
  2753.  
  2754.      setnetent(STAYOPEN)
  2755.  
  2756.      setprotoent(STAYOPEN)
  2757.  
  2758.      setservent(STAYOPEN)
  2759.  
  2760.      endpwent
  2761.  
  2762.      endgrent
  2763.  
  2764.      endhostent
  2765.  
  2766.  
  2767.  
  2768.  
  2769. Consensys Computer Inc.                                        42
  2770.  
  2771.  
  2772.  
  2773.  
  2774.  
  2775.  
  2776. PERL(1)                  USER COMMANDS                    PERL(1)
  2777.  
  2778.  
  2779.  
  2780.      endnetent
  2781.  
  2782.      endprotoent
  2783.  
  2784.      endservent
  2785.              These routines perform the same functions  as  their
  2786.              counterparts  in the system library.  (None are sup-
  2787.              ported on MS-DOS.)  The return values from the vari-
  2788.              ous get routines are as follows:
  2789.  
  2790.                   ($name,$passwd,$uid,$gid,
  2791.                      $quota,$comment,$gcos,$dir,$shell) = getpw...
  2792.                   ($name,$passwd,$gid,$members) = getgr...
  2793.                   ($name,$aliases,$addrtype,$length,@addrs) = gethost...
  2794.                   ($name,$aliases,$addrtype,$net) = getnet...
  2795.                   ($name,$aliases,$proto) = getproto...
  2796.                   ($name,$aliases,$port,$proto) = getserv...
  2797.  
  2798.              The $members value returned by getgr... is  a  space
  2799.              separated  list of the login names of the members of
  2800.              the group.
  2801.  
  2802.              The @addrs value returned by  the  gethost...  func-
  2803.              tions is a list of the raw addresses returned by the
  2804.              corresponding system library call.  In the  Internet
  2805.              domain,  each address is four bytes long and you can
  2806.              unpack it by saying something like:
  2807.  
  2808.                   ($a,$b,$c,$d) = unpack('C4',$addr[0]);
  2809.  
  2810.  
  2811.  
  2812.      getsockname(SOCKET)
  2813.              Returns the packed sockaddr address of this  end  of
  2814.              the SOCKET connection.
  2815.  
  2816.                   # An internet sockaddr
  2817.                   $sockaddr = 'S n a4 x8';
  2818.                   $mysockaddr = getsockname(S);
  2819.                   ($family, $port, $myaddr) =
  2820.                             unpack($sockaddr,$mysockaddr);
  2821.  
  2822.              Sockets are not yet supported on MS-DOS.
  2823.  
  2824.      getsockopt(SOCKET,LEVEL,OPTNAME)
  2825.              Returns the socket option requested, or undefined if
  2826.              there is an error.  Sockets are not yet supported on
  2827.              MS-DOS.
  2828.  
  2829.      gmtime(EXPR)
  2830.  
  2831.  
  2832.  
  2833.  
  2834.  
  2835. Consensys Computer Inc.                                        43
  2836.  
  2837.  
  2838.  
  2839.  
  2840.  
  2841.  
  2842. PERL(1)                  USER COMMANDS                    PERL(1)
  2843.  
  2844.  
  2845.  
  2846.      gmtime EXPR
  2847.              Converts a time as returned by the time function  to
  2848.              a  9-element  array  with  the time analyzed for the
  2849.              Greenwich timezone.  Typically used as follows:
  2850.  
  2851.              ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  2852.                                            gmtime(time);
  2853.  
  2854.              All array elements are numeric,  and  come  straight
  2855.              out  of  a struct tm.  In particular this means that
  2856.              $mon has the range 0..11 and  $wday  has  the  range
  2857.              0..6.  If EXPR is omitted, does gmtime(time).
  2858.  
  2859.      goto LABEL
  2860.              Finds the statement labeled with LABEL  and  resumes
  2861.              execution  there.   Currently  you  may  only  go to
  2862.              statements in the main body of the program that  are
  2863.              not nested inside a do {} construct.  This statement
  2864.              is not implemented very  efficiently,  and  is  here
  2865.              only  to  make the _s_e_d-to-_p_e_r_l translator easier.  I
  2866.              may change its semantics  at  any  time,  consistent
  2867.              with  support for translated _s_e_d scripts.  Use it at
  2868.              your own risk.  Better yet, don't use it at all.
  2869.  
  2870.      grep(EXPR,LIST)
  2871.              Evaluates EXPR for each  element  of  LIST  (locally
  2872.              setting  $_  to  each element) and returns the array
  2873.              value consisting of those  elements  for  which  the
  2874.              expression  evaluated to true.  In a scalar context,
  2875.              returns the number of times the expression was true.
  2876.  
  2877.                   @foo = grep(!/^#/, @bar);    # weed out comments
  2878.  
  2879.              Note that, since $_ is a reference  into  the  array
  2880.              value,  it can be used to modify the elements of the
  2881.              array.  While this is useful and supported,  it  can
  2882.              cause  bizarre  results  if  the LIST is not a named
  2883.              array.
  2884.  
  2885.      hex(EXPR)
  2886.  
  2887.      hex EXPR
  2888.              Returns the decimal value of EXPR interpreted as  an
  2889.              hex  string.  (To interpret strings that might start
  2890.              with 0 or 0x see oct().)  If EXPR is  omitted,  uses
  2891.              $_.
  2892.  
  2893.      index(STR,SUBSTR,POSITION)
  2894.  
  2895.      index(STR,SUBSTR)
  2896.              Returns the position  of  the  first  occurrence  of
  2897.              SUBSTR  in STR at or after POSITION.  If POSITION is
  2898.  
  2899.  
  2900.  
  2901. Consensys Computer Inc.                                        44
  2902.  
  2903.  
  2904.  
  2905.  
  2906.  
  2907.  
  2908. PERL(1)                  USER COMMANDS                    PERL(1)
  2909.  
  2910.  
  2911.  
  2912.              omitted, starts searching from the beginning of  the
  2913.              string.  The return value is based at 0, or whatever
  2914.              you've set the $[ variable to.  If the substring  is
  2915.              not  found,  returns  one  less than the base, ordi-
  2916.              narily -1.
  2917.  
  2918.      int(EXPR)
  2919.  
  2920.      int EXPR
  2921.              Returns the integer portion of  EXPR.   If  EXPR  is
  2922.              omitted, uses $_.
  2923.  
  2924.      ioctl(FILEHANDLE,FUNCTION,SCALAR)
  2925.              Implements the Unix ioctl(2) function.  You'll prob-
  2926.              ably have to say
  2927.  
  2928.                   require "ioctl.ph"; # probably /usr/local/lib/perl/ioctl.ph
  2929.  
  2930.              first to get the correct function  definitions.   If
  2931.              ioctl.ph  doesn't  exist or doesn't have the correct
  2932.              definitions you'll have to roll your own,  based  on
  2933.              your  C  header files such as <sys/ioctl.h>.  (There
  2934.              is a perl script called h2ph  that  comes  with  the
  2935.              Unix  perl  kit which may help you in this.)  SCALAR
  2936.              will  be  read  and/or  written  depending  on   the
  2937.              FUNCTION--a  pointer  to  the string value of SCALAR
  2938.              will be passed as the third argument of  the  actual
  2939.              ioctl call.  (If SCALAR has no string value but does
  2940.              have a numeric value,  that  value  will  be  passed
  2941.              rather  than  a  pointer  to  the  string value.  To
  2942.              guarantee this to be true, add a  0  to  the  scalar
  2943.              before using it.)  The pack() and unpack() functions
  2944.              are useful for manipulating the values of structures
  2945.              used  by  ioctl().   The  following example sets the
  2946.              erase character to DEL.
  2947.  
  2948.                   require 'ioctl.ph';
  2949.                   $sgttyb_t = "ccccs";          # 4 chars and a short
  2950.                   if (ioctl(STDIN,$TIOCGETP,$sgttyb)) {
  2951.                        @ary = unpack($sgttyb_t,$sgttyb);
  2952.                        $ary[2] = 127;
  2953.                        $sgttyb = pack($sgttyb_t,@ary);
  2954.                        ioctl(STDIN,$TIOCSETP,$sgttyb)
  2955.                             || die "Can't ioctl: $!";
  2956.                   }
  2957.  
  2958.              The return value of ioctl (and fcntl) is as follows:
  2959.  
  2960.                   if OS returns:           perl returns:
  2961.                     -1                       undefined value
  2962.                     0                        string "0 but true"
  2963.                     anything else            that number
  2964.  
  2965.  
  2966.  
  2967. Consensys Computer Inc.                                        45
  2968.  
  2969.  
  2970.  
  2971.  
  2972.  
  2973.  
  2974. PERL(1)                  USER COMMANDS                    PERL(1)
  2975.  
  2976.  
  2977.  
  2978.              Thus perl returns  true  on  success  and  false  on
  2979.              failure,  yet  you  can  still  easily determine the
  2980.              actual value returned by the operating system:
  2981.  
  2982.                   ($retval = ioctl(...)) || ($retval = -1);
  2983.                   printf "System returned %d\n", $retval;
  2984.  
  2985.  
  2986.              On MS-DOS, the function code of the  ioctl  function
  2987.              (the second argument) is encoded as follows:
  2988.  
  2989.                   The lowest nibble of the function code goes to AL.
  2990.                   The two middle nibbles go to CL.
  2991.                   The high nibble goes to CH.
  2992.  
  2993.              The return code is -1 in the case of an error and if
  2994.              successful:
  2995.  
  2996.                   for functions AL = 00, 09, 0a the value of the register DX
  2997.                   for functions AL = 02 - 08, 0e the value of the register AX
  2998.                   for functions AL = 01, 0b - 0f the number 0.
  2999.  
  3000.  
  3001.              The program can distiguish between the return  value
  3002.              and  the  success  of  ioctl  as  described for Unix
  3003.              above.
  3004.  
  3005.              Some MS-DOS ioctl functions need  a  number  as  the
  3006.              first  argument.   Provided that no other files have
  3007.              been opened the number can be obtained if  ioctl  is
  3008.              called  with  @fdnum[number]  as  the first argument
  3009.              after executing the following code:
  3010.  
  3011.                   @fdnum = ("STDIN", "STDOUT", "STDERR");
  3012.                   $maxdrives = 15;
  3013.                   for ($i = 3; $i < $maxdrives; $i++) {
  3014.                        open("FD$i", "nul");
  3015.                        @fdnum[$i - 1] = "FD$i";
  3016.                   }
  3017.  
  3018.  
  3019.      join(EXPR,LIST)
  3020.  
  3021.      join(EXPR,ARRAY)
  3022.              Joins the separate strings of LIST or ARRAY  into  a
  3023.              single  string with fields separated by the value of
  3024.              EXPR, and returns the string.  Example:
  3025.  
  3026.              $_ = join(':',
  3027.                        $login,$passwd,$uid,$gid,$gcos,$home,$shell);
  3028.  
  3029.              See _s_p_l_i_t.
  3030.  
  3031.  
  3032.  
  3033. Consensys Computer Inc.                                        46
  3034.  
  3035.  
  3036.  
  3037.  
  3038.  
  3039.  
  3040. PERL(1)                  USER COMMANDS                    PERL(1)
  3041.  
  3042.  
  3043.  
  3044.      keys(ASSOC_ARRAY)
  3045.  
  3046.      keys ASSOC_ARRAY
  3047.              Returns a normal array consisting of all the keys of
  3048.              the  named associative array.  The keys are returned
  3049.              in an apparently random order, but it  is  the  same
  3050.              order as either the values() or each() function pro-
  3051.              duces (given that the associative array has not been
  3052.              modified).   Here  is  yet another way to print your
  3053.              environment:
  3054.  
  3055.                   @keys = keys %ENV;
  3056.                   @values = values %ENV;
  3057.                   while ($#keys >= 0) {
  3058.                        print pop(@keys), '=', pop(@values), "\n";
  3059.                   }
  3060.  
  3061.              or how about sorted by key:
  3062.  
  3063.                   foreach $key (sort(keys %ENV)) {
  3064.                        print $key, '=', $ENV{$key}, "\n";
  3065.                   }
  3066.  
  3067.  
  3068.      kill(LIST)
  3069.  
  3070.      kill LIST
  3071.              Sends a signal to a list of  processes.   The  first
  3072.              element  of  the  list  must  be the signal to send.
  3073.              Returns the number of  processes  successfully  sig-
  3074.              naled.
  3075.  
  3076.                   $cnt = kill 1, $child1, $child2;
  3077.                   kill 9, @goners;
  3078.  
  3079.              If the signal  is  negative,  kills  process  groups
  3080.              instead of processes.  (On System V, a negative _p_r_o_-
  3081.              _c_e_s_s number  will  also  kill  process  groups,  but
  3082.              that's  not portable.)  You may use a signal name in
  3083.              quotes.   Not supported on MS-DOS.
  3084.  
  3085.      last LABEL
  3086.  
  3087.      last    The _l_a_s_t command is like the _b_r_e_a_k  statement  in  C
  3088.              (as used in loops); it immediately exits the loop in
  3089.              question.  If the  LABEL  is  omitted,  the  command
  3090.              refers  to  the  innermost enclosing loop.  The _c_o_n_-
  3091.              _t_i_n_u_e block, if any, is not executed:
  3092.  
  3093.  
  3094.  
  3095.  
  3096.  
  3097.  
  3098.  
  3099. Consensys Computer Inc.                                        47
  3100.  
  3101.  
  3102.  
  3103.  
  3104.  
  3105.  
  3106. PERL(1)                  USER COMMANDS                    PERL(1)
  3107.  
  3108.  
  3109.  
  3110.                   line: while (<STDIN>) {
  3111.                        last line if /^$/;  # exit when done with header
  3112.                        ...
  3113.                   }
  3114.  
  3115.  
  3116.      length(EXPR)
  3117.  
  3118.      length EXPR
  3119.              Returns the length in characters  of  the  value  of
  3120.              EXPR.  If EXPR is omitted, returns length of $_.
  3121.  
  3122.      link(OLDFILE,NEWFILE)
  3123.              Creates a new filename linked to the  old  filename.
  3124.              Returns  1  for success, 0 otherwise.  Not supported
  3125.              on MS-DOS.
  3126.  
  3127.      listen(SOCKET,QUEUESIZE)
  3128.              Does the same thing  that  the  listen  system  call
  3129.              does.   Returns  true  if it succeeded, false other-
  3130.              wise.  See example in section on  Interprocess  Com-
  3131.              munication.     Sockets are not yet supported on MS-
  3132.              DOS.
  3133.  
  3134.      local(LIST)
  3135.              Declares the listed variables to  be  local  to  the
  3136.              enclosing  block, subroutine, eval or "do".  All the
  3137.              listed elements must be legal lvalues.  This  opera-
  3138.              tor  works  by  saving  the  current values of those
  3139.              variables in LIST on a hidden  stack  and  restoring
  3140.              them  upon  exiting  the  block, subroutine or eval.
  3141.              This means that called subroutines can  also  refer-
  3142.              ence  the  local  variable,  but not the global one.
  3143.              The LIST may be assigned to if desired, which allows
  3144.              you to initialize your local variables.  (If no ini-
  3145.              tializer is given for a particular variable,  it  is
  3146.              created  with an undefined value.)  Commonly this is
  3147.              used to name the parameters to a subroutine.   Exam-
  3148.              ples:
  3149.  
  3150.  
  3151.  
  3152.  
  3153.  
  3154.  
  3155.  
  3156.  
  3157.  
  3158.  
  3159.  
  3160.  
  3161.  
  3162.  
  3163.  
  3164.  
  3165. Consensys Computer Inc.                                        48
  3166.  
  3167.  
  3168.  
  3169.  
  3170.  
  3171.  
  3172. PERL(1)                  USER COMMANDS                    PERL(1)
  3173.  
  3174.  
  3175.  
  3176.                   sub RANGEVAL {
  3177.                        local($min, $max, $thunk) = @_;
  3178.                        local($result) = '';
  3179.                        local($i);
  3180.  
  3181.                        # Presumably $thunk makes reference to $i
  3182.  
  3183.                        for ($i = $min; $i < $max; $i++) {
  3184.                             $result .= eval $thunk;
  3185.                        }
  3186.  
  3187.                        $result;
  3188.                   }
  3189.  
  3190.                   if ($sw eq '-v') {
  3191.                       # init local array with global array
  3192.                       local(@ARGV) = @ARGV;
  3193.                       unshift(@ARGV,'echo');
  3194.                       system @ARGV;
  3195.                   }
  3196.                   # @ARGV restored
  3197.  
  3198.                   # temporarily add to digits associative array
  3199.                   if ($base12) {
  3200.                        # (NOTE: not claiming this is efficient!)
  3201.                        local(%digits) = (%digits,'t',10,'e',11);
  3202.                        do parse_num();
  3203.                   }
  3204.  
  3205.              Note that local() is a run-time command, and so gets
  3206.              executed  every  time  through a loop, using up more
  3207.              stack storage each time until it's all  released  at
  3208.              once when the loop is exited.
  3209.  
  3210.      localtime(EXPR)
  3211.  
  3212.      localtime EXPR
  3213.              Converts a time as returned by the time function  to
  3214.              a  9-element  array  with  the time analyzed for the
  3215.              local timezone.  Typically used as follows:
  3216.  
  3217.              ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  3218.                                            localtime(time);
  3219.  
  3220.              All array elements are numeric,  and  come  straight
  3221.              out  of  a struct tm.  In particular this means that
  3222.              $mon has the range 0..11 and  $wday  has  the  range
  3223.              0..6.  If EXPR is omitted, does localtime(time).
  3224.  
  3225.      log(EXPR)
  3226.  
  3227.  
  3228.  
  3229.  
  3230.  
  3231. Consensys Computer Inc.                                        49
  3232.  
  3233.  
  3234.  
  3235.  
  3236.  
  3237.  
  3238. PERL(1)                  USER COMMANDS                    PERL(1)
  3239.  
  3240.  
  3241.  
  3242.      log EXPR
  3243.              Returns logarithm (base _e)  of  EXPR.   If  EXPR  is
  3244.              omitted, returns log of $_.
  3245.  
  3246.      lstat(FILEHANDLE)
  3247.  
  3248.      lstat FILEHANDLE
  3249.  
  3250.      lstat(EXPR)
  3251.  
  3252.      lstat SCALARVARIABLE
  3253.              Does the same thing  as  the  stat()  function,  but
  3254.              stats  a  symbolic link instead of the file the sym-
  3255.              bolic link points to.  If symbolic links  are  unim-
  3256.              plemented on your system, a normal stat is done.
  3257.  
  3258.      m/PATTERN/gio
  3259.  
  3260.      /PATTERN/gio
  3261.              Searches a string for a pattern match,  and  returns
  3262.              true  (1)  or false ('').  If no string is specified
  3263.              via  the  =~  or  !~  operator,  the  $_  string  is
  3264.              searched.  (The string specified with =~ need not be
  3265.              an lvalue--it may be the  result  of  an  expression
  3266.              evaluation,   but   remember  the  =~  binds  rather
  3267.              tightly.)  See also the section on  regular  expres-
  3268.              sions.
  3269.  
  3270.              If / is  the  delimiter  then  the  initial  'm'  is
  3271.              optional.   With  the  'm'  you  can use any pair of
  3272.              non-alphanumeric characters as delimiters.  This  is
  3273.              particularly  useful  for  matching  Unix path names
  3274.              that contain '/'.  If the final  delimiter  is  fol-
  3275.              lowed  by  the  optional letter 'i', the matching is
  3276.              done in a case-insensitive manner.  PATTERN may con-
  3277.              tain  references  to scalar variables, which will be
  3278.              interpolated (and the pattern recompiled) every time
  3279.              the  pattern search is evaluated.  (Note that $) and
  3280.              $| may not be interpolated because  they  look  like
  3281.              end-of-string tests.)  If you want such a pattern to
  3282.              be compiled only once, add an "o" after the trailing
  3283.              delimiter.   This avoids expensive run-time recompi-
  3284.              lations, and is useful when the value you are inter-
  3285.              polating  won't  change over the life of the script.
  3286.              If the PATTERN evaluates to a null string, the  most
  3287.              recent   successful   regular   expression  is  used
  3288.              instead.
  3289.  
  3290.              If used in a context that requires an array value, a
  3291.              pattern  match  returns  an  array consisting of the
  3292.              subexpressions matched by  the  parentheses  in  the
  3293.              pattern, i.e. ($1, $2, $3...).  It does NOT actually
  3294.  
  3295.  
  3296.  
  3297. Consensys Computer Inc.                                        50
  3298.  
  3299.  
  3300.  
  3301.  
  3302.  
  3303.  
  3304. PERL(1)                  USER COMMANDS                    PERL(1)
  3305.  
  3306.  
  3307.  
  3308.              set $1, $2, etc. in this case, nor does it  set  $+,
  3309.              $`,  $&  or $'.  If the match fails, a null array is
  3310.              returned.  If the match succeeds, but there were  no
  3311.              parentheses, an array value of (1) is returned.
  3312.  
  3313.              Examples:
  3314.  
  3315.                  open(tty, '/dev/tty');
  3316.                  <tty> =~ /^y/i && do foo();    # do foo if desired
  3317.  
  3318.                  if (/Version: *([0-9.]*)/) { $version = $1; }
  3319.  
  3320.                  next if m#^/usr/spool/uucp#;
  3321.  
  3322.                  # poor man's grep
  3323.                  $arg = shift;
  3324.                  while (<>) {
  3325.                       print if /$arg/o;    # compile only once
  3326.                  }
  3327.  
  3328.                  if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))
  3329.  
  3330.              This last example splits $foo  into  the  first  two
  3331.              words  and  the  remainder  of the line, and assigns
  3332.              those three fields to $F1, $F2 and $Etc.  The condi-
  3333.              tional  is true if any variables were assigned, i.e.
  3334.              if the pattern matched.
  3335.  
  3336.              The   "g"   modifier   specifies   global    pattern
  3337.              matching--that  is, matching as many times as possi-
  3338.              ble within the string.  How it  behaves  depends  on
  3339.              the context.  In an array context, it returns a list
  3340.              of all the substrings matched by all the parentheses
  3341.              in   the   regular  expression.   If  there  are  no
  3342.              parentheses, it returns a list of  all  the  matched
  3343.              strings,  as  if  there  were parentheses around the
  3344.              whole pattern.  In a  scalar  context,  it  iterates
  3345.              through  the  string,  returning  TRUE  each time it
  3346.              matches, and FALSE when it eventually  runs  out  of
  3347.              matches.   (In  other  words,  it remembers where it
  3348.              left off last time and restarts the search  at  that
  3349.              point.)   It presumes that you have not modified the
  3350.              string since the last match.  Modifying  the  string
  3351.              between  matches  may  result in undefined behavior.
  3352.              (You can actually get away with  in-place  modifica-
  3353.              tions  via substr() that do not change the length of
  3354.              the entire string.  In general, however, you  should
  3355.              be using s///g for such modifications.)  Examples:
  3356.  
  3357.                   # array context
  3358.                   ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);
  3359.  
  3360.  
  3361.  
  3362.  
  3363. Consensys Computer Inc.                                        51
  3364.  
  3365.  
  3366.  
  3367.  
  3368.  
  3369.  
  3370. PERL(1)                  USER COMMANDS                    PERL(1)
  3371.  
  3372.  
  3373.  
  3374.                   # scalar context
  3375.                   $/ = 1; $* = 1;
  3376.                   while ($paragraph = <>) {
  3377.                       while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g) {
  3378.                        $sentences++;
  3379.                       }
  3380.                   }
  3381.                   print "$sentences\n";
  3382.  
  3383.  
  3384.      mkdir(FILENAME,MODE)
  3385.              Creates the directory specified  by  FILENAME,  with
  3386.              permissions   specified  by  MODE  (as  modified  by
  3387.              umask).  If it succeeds it returns 1,  otherwise  it
  3388.              returns 0 and sets $! (errno).
  3389.  
  3390.      msgctl(ID,CMD,ARG)
  3391.              Calls the System V IPC function msgctl.  If  CMD  is
  3392.              &IPC_STAT,  then  ARG  must be a variable which will
  3393.              hold the returned msqid_ds structure.  Returns  like
  3394.              ioctl:  the  undefined value for error, "0 but true"
  3395.              for zero, or  the  actual  return  value  otherwise.
  3396.              (The  message family is not available under MS-DOS.)
  3397.  
  3398.  
  3399.      msgget(KEY,FLAGS)
  3400.              Calls the System V IPC function msgget.  Returns the
  3401.              message queue id, or the undefined value if there is
  3402.              an error.
  3403.  
  3404.      msgsnd(ID,MSG,FLAGS)
  3405.              Calls the System V IPC function msgsnd to  send  the
  3406.              message MSG to the message queue ID.  MSG must begin
  3407.              with the long integer message  type,  which  may  be
  3408.              created with pack("L", $type).  Returns true if suc-
  3409.              cessful, or false if there is an error.
  3410.  
  3411.      msgrcv(ID,VAR,SIZE,TYPE,FLAGS)
  3412.              Calls the System V IPC function msgrcv to receive  a
  3413.              message from message queue ID into variable VAR with
  3414.              a maximum message size of SIZE.  Note that if a mes-
  3415.              sage is received, the message type will be the first
  3416.              thing in VAR, and the maximum length of VAR is  SIZE
  3417.              plus  the size of the message type.  Returns true if
  3418.              successful, or false if there is an error.
  3419.  
  3420.  
  3421.  
  3422.  
  3423.  
  3424.  
  3425.  
  3426.  
  3427.  
  3428.  
  3429. Consensys Computer Inc.                                        52
  3430.  
  3431.  
  3432.  
  3433.  
  3434.  
  3435.  
  3436. PERL(1)                  USER COMMANDS                    PERL(1)
  3437.  
  3438.  
  3439.  
  3440.      next LABEL
  3441.  
  3442.      next    The _n_e_x_t command is like the _c_o_n_t_i_n_u_e  statement  in
  3443.              C; it starts the next iteration of the loop:
  3444.  
  3445.                   line: while (<STDIN>) {
  3446.                        next line if /^#/;  # discard comments
  3447.                        ...
  3448.                   }
  3449.  
  3450.              Note that if there were  a  _c_o_n_t_i_n_u_e  block  on  the
  3451.              above,  it  would  get  executed  even  on discarded
  3452.              lines.  If the LABEL is omitted, the command  refers
  3453.              to the innermost enclosing loop.
  3454.  
  3455.      oct(EXPR)
  3456.  
  3457.      oct EXPR
  3458.              Returns the decimal value of EXPR interpreted as  an
  3459.              octal  string.   (If  EXPR happens to start off with
  3460.              0x, interprets it as a  hex  string  instead.)   The
  3461.              following  will handle decimal, octal and hex in the
  3462.              standard notation:
  3463.  
  3464.                   $val = oct($val) if $val =~ /^0/;
  3465.  
  3466.              If EXPR is omitted, uses $_.
  3467.  
  3468.      open(FILEHANDLE,EXPR)
  3469.  
  3470.      open(FILEHANDLE)
  3471.  
  3472.      open FILEHANDLE
  3473.              Opens the file whose filename is given by EXPR,  and
  3474.              associates  it with FILEHANDLE.  If FILEHANDLE is an
  3475.              expression, its value is used as  the  name  of  the
  3476.              real  filehandle  wanted.   If  EXPR is omitted, the
  3477.              scalar variable of the same name as  the  FILEHANDLE
  3478.              contains  the filename.  If the filename begins with
  3479.              "<" or nothing, the file is opened  for  input.   If
  3480.              the filename begins with ">", the file is opened for
  3481.              output.  If the filename begins with ">>", the  file
  3482.              is  opened  for  appending.   (You  can put a '+' in
  3483.              front of the '>' or '<' to indicate  that  you  want
  3484.              both  read  and  write  access to the file.)  If the
  3485.              filename begins with "|",  the  filename  is  inter-
  3486.              preted  as a command to which output is to be piped,
  3487.              and if the filename ends with a "|", the filename is
  3488.              interpreted  as  command  which  pipes  input to us.
  3489.              (You may not have a command that pipes both  in  and
  3490.              out.)   Opening  '-'  opens  _S_T_D_I_N  and opening '>-'
  3491.              opens _S_T_D_O_U_T.  Open returns non-zero  upon  success,
  3492.  
  3493.  
  3494.  
  3495. Consensys Computer Inc.                                        53
  3496.  
  3497.  
  3498.  
  3499.  
  3500.  
  3501.  
  3502. PERL(1)                  USER COMMANDS                    PERL(1)
  3503.  
  3504.  
  3505.  
  3506.              the undefined value otherwise.  If the open involved
  3507.              a pipe, the return value happens to be  the  pid  of
  3508.              the subprocess.  Examples:
  3509.  
  3510.                   $article = 100;
  3511.                   open article || die "Can't find article $article: $!\n";
  3512.                   while (<article>) {...
  3513.  
  3514.                   open(LOG, '>>/usr/spool/news/twitlog');
  3515.                                       # (log is reserved)
  3516.  
  3517.                   open(article, "caesar <$article |");
  3518.                                       # decrypt article
  3519.  
  3520.                   open(extract, "|sort >/tmp/Tmp$$");
  3521.                                       # $$ is our process#
  3522.  
  3523.                   # process argument list of files along with any includes
  3524.  
  3525.                   foreach $file (@ARGV) {
  3526.                        do process($file, 'fh00');    # no pun intended
  3527.                   }
  3528.  
  3529.                   sub process {
  3530.                        local($filename, $input) = @_;
  3531.                        $input++;      # this is a string increment
  3532.                        unless (open($input, $filename)) {
  3533.                             print STDERR "Can't open $filename: $!\n";
  3534.                             return;
  3535.                        }
  3536.                        while (<$input>) {       # note use of indirection
  3537.                             if (/^#include "(.*)"/) {
  3538.                                  do process($1, $input);
  3539.                                  next;
  3540.                             }
  3541.                             ...       # whatever
  3542.                        }
  3543.                   }
  3544.  
  3545.              You may also, in the Bourne shell tradition, specify
  3546.              an  EXPR beginning with ">&", in which case the rest
  3547.              of the string  is  interpreted  as  the  name  of  a
  3548.              filehandle (or file descriptor, if numeric) which is
  3549.              to be duped and opened.  You may use & after >,  >>,
  3550.              <,  +>,  +>>  and  +<.   The mode you specify should
  3551.              match the mode of the original filehandle.  Here  is
  3552.              a  script that saves, redirects, and restores _S_T_D_O_U_T
  3553.              and _S_T_D_E_R_R:
  3554.  
  3555.  
  3556.  
  3557.  
  3558.  
  3559.  
  3560.  
  3561. Consensys Computer Inc.                                        54
  3562.  
  3563.  
  3564.  
  3565.  
  3566.  
  3567.  
  3568. PERL(1)                  USER COMMANDS                    PERL(1)
  3569.  
  3570.  
  3571.  
  3572.                   #!/usr/bin/perl
  3573.                   open(SAVEOUT, ">&STDOUT");
  3574.                   open(SAVEERR, ">&STDERR");
  3575.  
  3576.                   open(STDOUT, ">foo.out") || die "Can't redirect stdout";
  3577.                   open(STDERR, ">&STDOUT") || die "Can't dup stdout";
  3578.  
  3579.                   select(STDERR); $| = 1;       # make unbuffered
  3580.                   select(STDOUT); $| = 1;       # make unbuffered
  3581.  
  3582.                   print STDOUT "stdout 1\n";    # this works for
  3583.                   print STDERR "stderr 1\n";    # subprocesses too
  3584.  
  3585.                   close(STDOUT);
  3586.                   close(STDERR);
  3587.  
  3588.                   open(STDOUT, ">&SAVEOUT");
  3589.                   open(STDERR, ">&SAVEERR");
  3590.  
  3591.                   print STDOUT "stdout 2\n";
  3592.                   print STDERR "stderr 2\n";
  3593.  
  3594.              If you open a pipe on the command "-",  i.e.  either
  3595.              "|-"  or  "-|", then there is an implicit fork done,
  3596.              and the return value of open is the pid of the child
  3597.              within  the  parent  process, and 0 within the child
  3598.              process.  (This  is  not  supported  under  MS-DOS.)
  3599.              (Use defined($pid) to determine if the open was suc-
  3600.              cessful.)  The filehandle behaves normally  for  the
  3601.              parent,  but i/o to that filehandle is piped from/to
  3602.              the _S_T_D_O_U_T/_S_T_D_I_N of the child process.  In the child
  3603.              process  the  filehandle  isn't  opened--i/o happens
  3604.              from/to the new _S_T_D_O_U_T or _S_T_D_I_N.  Typically this  is
  3605.              used  like  the  normal  piped open when you want to
  3606.              exercise more control over just how the pipe command
  3607.              gets  executed, such as when you are running setuid,
  3608.              and don't want to have to scan  shell  commands  for
  3609.              metacharacters.   The  following  pairs  are more or
  3610.              less equivalent:
  3611.  
  3612.                   open(FOO, "|tr '[a-z]' '[A-Z]'");
  3613.                   open(FOO, "|-") || exec 'tr', '[a-z]', '[A-Z]';
  3614.  
  3615.                   open(FOO, "cat -n '$file'|");
  3616.                   open(FOO, "-|") || exec 'cat', '-n', $file;
  3617.  
  3618.  
  3619.              Explicitly closing any piped filehandle  causes  the
  3620.              parent  process to wait for the child to finish, and
  3621.              returns the status value in $?.  Note: on any opera-
  3622.              tion  which  may do a fork, unflushed buffers remain
  3623.              unflushed in both processes,  which  means  you  may
  3624.  
  3625.  
  3626.  
  3627. Consensys Computer Inc.                                        55
  3628.  
  3629.  
  3630.  
  3631.  
  3632.  
  3633.  
  3634. PERL(1)                  USER COMMANDS                    PERL(1)
  3635.  
  3636.  
  3637.  
  3638.              need to set $| to avoid duplicate output.
  3639.  
  3640.              On MS-DOS, "pipes" are actually files, and the  sub-
  3641.              process is run to completion.  For output pipes, the
  3642.              subprocess is run when _p_e_r_l exits or when  the  pipe
  3643.              is  explicitly closed.  For input pipes, the subpro-
  3644.              gram is run to completion when the _o_p_e_n is  done.
  3645.              The  filename that is passed to open will have lead-
  3646.              ing and trailing whitespace deleted.   In  order  to
  3647.              open  a  file with arbitrary weird characters in it,
  3648.              it's necessary to protect any leading  and  trailing
  3649.              whitespace thusly:
  3650.  
  3651.                      $file =~ s#^(\s)#./$1#;
  3652.                      open(FOO, "< $file\0");
  3653.  
  3654.              On MS-DOS, it is recommended that forward slashes be
  3655.              used to delimit path components in file names.  (See
  3656.              the section on MS-DOS considerations.)
  3657.  
  3658.      opendir(DIRHANDLE,EXPR)
  3659.              Opens a directory named EXPR for processing by read-
  3660.              dir(),   telldir(),   seekdir(),   rewinddir()   and
  3661.              closedir().  Returns true if successful.  DIRHANDLEs
  3662.              have their own namespace separate from FILEHANDLEs.
  3663.  
  3664.      ord(EXPR)
  3665.  
  3666.      ord EXPR
  3667.              Returns the numeric ascii value of the first charac-
  3668.              ter of EXPR.  If EXPR is omitted, uses $_.
  3669.  
  3670.      pack(TEMPLATE,LIST)
  3671.              Takes an array or list of values and packs it into a
  3672.              binary  structure,  returning  the string containing
  3673.              the structure.  The TEMPLATE is a sequence of  char-
  3674.              acters  that  give  the order and type of values, as
  3675.              follows:
  3676.  
  3677.                   A    An ascii string, will be space padded.
  3678.                   a    An ascii string, will be null padded.
  3679.                   c    A signed char value.
  3680.                   C    An unsigned char value.
  3681.                   s    A signed short value.
  3682.                   S    An unsigned short value.
  3683.                   i    A signed integer value.
  3684.                   I    An unsigned integer value.
  3685.                   l    A signed long value.
  3686.                   L    An unsigned long value.
  3687.                   n    A short in "network" order.
  3688.                   N    A long in "network" order.
  3689.                   f    A single-precision float in the native format.
  3690.  
  3691.  
  3692.  
  3693. Consensys Computer Inc.                                        56
  3694.  
  3695.  
  3696.  
  3697.  
  3698.  
  3699.  
  3700. PERL(1)                  USER COMMANDS                    PERL(1)
  3701.  
  3702.  
  3703.  
  3704.                   d    A double-precision float in the native format.
  3705.                   p    A pointer to a string.
  3706.                   v    A short in "VAX" (little-endian) order.
  3707.                   V    A long in "VAX" (little-endian) order.
  3708.                   x    A null byte.
  3709.                   X    Back up a byte.
  3710.                   @    Null fill to absolute position.
  3711.                   u    A uuencoded string.
  3712.                   b    A bit string (ascending bit order, like vec()).
  3713.                   B    A bit string (descending bit order).
  3714.                   h    A hex string (low nybble first).
  3715.                   H    A hex string (high nybble first).
  3716.  
  3717.              Each letter may optionally be followed by  a  number
  3718.              which  gives  a repeat count.  With all types except
  3719.              "a", "A", "b", "B", "h" and "H", the  pack  function
  3720.              will  gobble up that many values from the LIST.  A *
  3721.              for the repeat count means to use however many items
  3722.              are  left.   The  "a"  and "A" types gobble just one
  3723.              value, but pack it as a string of length count, pad-
  3724.              ding  with  nulls  or  spaces  as  necessary.  (When
  3725.              unpacking, "A" strips trailing spaces and nulls, but
  3726.              "a"  does  not.)   Likewise,  the "b" and "B" fields
  3727.              pack a string that many bits long.  The "h" and  "H"
  3728.              fields  pack  a string that many nybbles long.  Real
  3729.              numbers (floats  and  doubles)  are  in  the  native
  3730.              machine  format  only;  due  to  the multiplicity of
  3731.              floating formats around, and the lack of a  standard
  3732.              "network"  representation,  no  facility  for inter-
  3733.              change has been made.  This means that packed float-
  3734.              ing  point  data  written  on one machine may not be
  3735.              readable on another - even if both use IEEE floating
  3736.              point  arithmetic  (as the endian-ness of the memory
  3737.              representation is not part of the IEEE spec).   Note
  3738.              that  perl  uses  doubles internally for all numeric
  3739.              calculation, and converting from double -> float  ->
  3740.              double   will   lose   precision  (i.e.  unpack("f",
  3741.              pack("f", $foo)) will not in general equal $foo).
  3742.              Examples:
  3743.  
  3744.                   $foo = pack("cccc",65,66,67,68);
  3745.                   # foo eq "ABCD"
  3746.                   $foo = pack("c4",65,66,67,68);
  3747.                   # same thing
  3748.  
  3749.                   $foo = pack("ccxxcc",65,66,67,68);
  3750.                   # foo eq "AB\0\0CD"
  3751.  
  3752.                   $foo = pack("s2",1,2);
  3753.                   # "\1\0\2\0" on little-endian
  3754.                   # "\0\1\0\2" on big-endian
  3755.  
  3756.  
  3757.  
  3758.  
  3759. Consensys Computer Inc.                                        57
  3760.  
  3761.  
  3762.  
  3763.  
  3764.  
  3765.  
  3766. PERL(1)                  USER COMMANDS                    PERL(1)
  3767.  
  3768.  
  3769.  
  3770.                   $foo = pack("a4","abcd","x","y","z");
  3771.                   # "abcd"
  3772.  
  3773.                   $foo = pack("aaaa","abcd","x","y","z");
  3774.                   # "axyz"
  3775.  
  3776.                   $foo = pack("a14","abcdefg");
  3777.                   # "abcdefg\0\0\0\0\0\0\0"
  3778.  
  3779.                   $foo = pack("i9pl", gmtime);
  3780.                   # a real struct tm (on my system anyway)
  3781.  
  3782.                   sub bintodec {
  3783.                       unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
  3784.                   }
  3785.              The same template may generally also be used in  the
  3786.              unpack function.
  3787.  
  3788.      pipe(READHANDLE,WRITEHANDLE)
  3789.              Opens a pair of connected pipes like the correspond-
  3790.              ing  system call.  Note that if you set up a loop of
  3791.              piped processes, deadlock can occur unless  you  are
  3792.              very  careful.   In addition, note that perl's pipes
  3793.              use stdio buffering, so you may need to  set  $|  to
  3794.              flush your WRITEHANDLE after each command, depending
  3795.              on   the   application.    [Requires   version   3.0
  3796.              patchlevel 9.]   Not supported on MS-DOS.
  3797.  
  3798.      pop(ARRAY)
  3799.  
  3800.      pop ARRAY
  3801.              Pops and returns the last value of the array,  shor-
  3802.              tening the array by 1.  Has the same effect as
  3803.  
  3804.                   $tmp = $ARRAY[$#ARRAY--];
  3805.  
  3806.              If there are no elements in the array,  returns  the
  3807.              undefined value.
  3808.  
  3809.      print(FILEHANDLE LIST)
  3810.  
  3811.      print(LIST)
  3812.  
  3813.      print FILEHANDLE LIST
  3814.  
  3815.      print LIST
  3816.  
  3817.      print   Prints  a  string  or  a  comma-separated  list   of
  3818.              strings.   Returns non-zero if successful.  FILEHAN-
  3819.              DLE may be a scalar variable name, in which case the
  3820.              variable  contains  the name of the filehandle, thus
  3821.              introducing one level  of  indirection.   (NOTE:  If
  3822.  
  3823.  
  3824.  
  3825. Consensys Computer Inc.                                        58
  3826.  
  3827.  
  3828.  
  3829.  
  3830.  
  3831.  
  3832. PERL(1)                  USER COMMANDS                    PERL(1)
  3833.  
  3834.  
  3835.  
  3836.              FILEHANDLE  is  a  variable  and the next token is a
  3837.              term, it may be misinterpreted as an operator unless
  3838.              you  interpose  a  +  or put parens around the argu-
  3839.              ments.)  If FILEHANDLE is omitted, prints by default
  3840.              to  standard  output (or to the last selected output
  3841.              channel--see select()).  If LIST  is  also  omitted,
  3842.              prints  $_  to  _S_T_D_O_U_T.   To  set the default output
  3843.              channel to  something  other  than  _S_T_D_O_U_T  use  the
  3844.              select  operation.  Note that, because print takes a
  3845.              LIST, anything in the LIST is evaluated in an  array
  3846.              context,  and any subroutine that you call will have
  3847.              one or more of its expressions evaluated in an array
  3848.              context.   Also  be  careful not to follow the print
  3849.              keyword with a left parenthesis unless you want  the
  3850.              corresponding  right  parenthesis  to  terminate the
  3851.              arguments to the print--interpose a + or put  parens
  3852.              around all the arguments.
  3853.  
  3854.      printf(FILEHANDLE LIST)
  3855.  
  3856.      printf(LIST)
  3857.  
  3858.      printf FILEHANDLE LIST
  3859.  
  3860.      printf LIST
  3861.              Equivalent to a "print FILEHANDLE sprintf(LIST)".
  3862.  
  3863.      push(ARRAY,LIST)
  3864.              Treats ARRAY (@ is optional) as a stack, and  pushes
  3865.              the  values  of  LIST  onto  the  end of ARRAY.  The
  3866.              length of ARRAY increases by  the  length  of  LIST.
  3867.              Has the same effect as
  3868.  
  3869.                  for $value (LIST) {
  3870.                       $ARRAY[++$#ARRAY] = $value;
  3871.                  }
  3872.  
  3873.              but is more efficient.
  3874.  
  3875.      q/STRING/
  3876.  
  3877.      qq/STRING/
  3878.  
  3879.      qx/STRING/
  3880.              These are not really functions, but simply syntactic
  3881.              sugar  to let you avoid putting too many backslashes
  3882.              into quoted strings.  The q operator is  a  general-
  3883.              ized single quote, and the qq operator a generalized
  3884.              double quote.  The  qx  operator  is  a  generalized
  3885.              backquote.   Any  non-alphanumeric  delimiter can be
  3886.              used in place of /, including newline.  If the  del-
  3887.              imiter  is  an  opening  bracket or parenthesis, the
  3888.  
  3889.  
  3890.  
  3891. Consensys Computer Inc.                                        59
  3892.  
  3893.  
  3894.  
  3895.  
  3896.  
  3897.  
  3898. PERL(1)                  USER COMMANDS                    PERL(1)
  3899.  
  3900.  
  3901.  
  3902.              final delimiter will be  the  corresponding  closing
  3903.              bracket  or  parenthesis.   (Embedded occurrences of
  3904.              the  closing  bracket  need  to  be  backslashed  as
  3905.              usual.)  Examples:
  3906.  
  3907.                   $foo = q!I said, "You said, 'She said it.'"!;
  3908.                   $bar = q('This is it.');
  3909.                   $today = qx{ date };
  3910.                   $_ .= qq
  3911.              *** The previous line contains the naughty word "$&".\n
  3912.                        if /(ibm|apple|awk)/;      # :-)
  3913.  
  3914.  
  3915.      rand(EXPR)
  3916.  
  3917.      rand EXPR
  3918.  
  3919.      rand    Returns a random fractional number between 0 and the
  3920.              value  of EXPR.  (EXPR should be positive.)  If EXPR
  3921.              is omitted, returns a value between 0  and  1.   See
  3922.              also srand().
  3923.  
  3924.      read(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  3925.  
  3926.      read(FILEHANDLE,SCALAR,LENGTH)
  3927.              Attempts to read LENGTH bytes of data into  variable
  3928.              SCALAR  from  the specified FILEHANDLE.  Returns the
  3929.              number of bytes actually read, or undef if there was
  3930.              an  error.   SCALAR  will  be grown or shrunk to the
  3931.              length actually read.  An OFFSET may be specified to
  3932.              place  the  read  data  at some other place than the
  3933.              beginning of the  string.   This  call  is  actually
  3934.              implemented  in terms of stdio's fread call.  To get
  3935.              a true read system call, see sysread.
  3936.  
  3937.      readdir(DIRHANDLE)
  3938.  
  3939.      readdir DIRHANDLE
  3940.              Returns the next directory  entry  for  a  directory
  3941.              opened  by  opendir().  If used in an array context,
  3942.              returns all the rest of the entries  in  the  direc-
  3943.              tory.   If  there  are  no  more entries, returns an
  3944.              undefined value in a scalar context or a  null  list
  3945.              in an array context.
  3946.  
  3947.      readlink(EXPR)
  3948.  
  3949.      readlink EXPR
  3950.              Returns the value of a symbolic  link,  if  symbolic
  3951.              links are implemented.  If not, gives a fatal error.
  3952.              If there is some system error, returns the undefined
  3953.              value and sets $! (errno).  If EXPR is omitted, uses
  3954.  
  3955.  
  3956.  
  3957. Consensys Computer Inc.                                        60
  3958.  
  3959.  
  3960.  
  3961.  
  3962.  
  3963.  
  3964. PERL(1)                  USER COMMANDS                    PERL(1)
  3965.  
  3966.  
  3967.  
  3968.              $_.   Not supported on MS-DOS.
  3969.  
  3970.      recv(SOCKET,SCALAR,LEN,FLAGS)
  3971.              Receives a message on a socket.
  3972.  
  3973.              SOCKET  filehandle.   Returns  the  address  of  the
  3974.              sender,  or the undefined value if there's an error.
  3975.              SCALAR will be grown or shrunk to the  length  actu-
  3976.              ally  read.  Takes the same flags as the system call
  3977.              of the same name.   Sockets are not yet supported on
  3978.              MS-DOS.
  3979.  
  3980.      redo LABEL
  3981.  
  3982.      redo    The _r_e_d_o command restarts  the  loop  block  without
  3983.              evaluating  the  conditional  again.   The  _c_o_n_t_i_n_u_e
  3984.              block, if any, is not executed.   If  the  LABEL  is
  3985.              omitted, the command refers to the innermost enclos-
  3986.              ing loop.  This command is normally used by programs
  3987.              that  want  to lie to themselves about what was just
  3988.              input:
  3989.  
  3990.                   # a simpleminded Pascal comment stripper
  3991.                   # (warning: assumes no { or } in strings)
  3992.                   line: while (<STDIN>) {
  3993.                        while (s|({.*}.*){.*}|$1 |) {}
  3994.                        s|{.*}| |;
  3995.                        if (s|{.*| |) {
  3996.                             $front = $_;
  3997.                             while (<STDIN>) {
  3998.                                  if (/}/) {     # end of comment?
  3999.                                       s|^|$front{|;
  4000.                                       redo line;
  4001.                                  }
  4002.                             }
  4003.                        }
  4004.                        print;
  4005.                   }
  4006.  
  4007.  
  4008.      rename(OLDNAME,NEWNAME)
  4009.              Changes the name of a file.  Returns 1 for  success,
  4010.              0  otherwise.  Will not work across filesystem boun-
  4011.              daries.
  4012.  
  4013.      require(EXPR)
  4014.  
  4015.      require EXPR
  4016.  
  4017.      require Includes the library file specified by EXPR,  or  by
  4018.              $_  if  EXPR is not supplied.  Has semantics similar
  4019.              to the following subroutine:
  4020.  
  4021.  
  4022.  
  4023. Consensys Computer Inc.                                        61
  4024.  
  4025.  
  4026.  
  4027.  
  4028.  
  4029.  
  4030. PERL(1)                  USER COMMANDS                    PERL(1)
  4031.  
  4032.  
  4033.  
  4034.                   sub require {
  4035.                       local($filename) = @_;
  4036.                       return 1 if $INC{$filename};
  4037.                       local($realfilename,$result);
  4038.                       ITER: {
  4039.                        foreach $prefix (@INC) {
  4040.                            $realfilename = "$prefix/$filename";
  4041.                            if (-f $realfilename) {
  4042.                             $result = do $realfilename;
  4043.                             last ITER;
  4044.                            }
  4045.                        }
  4046.                        die "Can't find $filename in \@INC";
  4047.                       }
  4048.                       die $@ if $@;
  4049.                       die "$filename did not return true value" unless $result;
  4050.                       $INC{$filename} = $realfilename;
  4051.                       $result;
  4052.                   }
  4053.  
  4054.              Note that the file will not be included twice  under
  4055.              the same specified name.
  4056.  
  4057.      reset(EXPR)
  4058.  
  4059.      reset EXPR
  4060.  
  4061.      reset   Generally used in a _c_o_n_t_i_n_u_e block at the end  of  a
  4062.              loop  to  clear  variables  and reset ?? searches so
  4063.              that they work again.  The expression is interpreted
  4064.              as  a list of single characters (hyphens allowed for
  4065.              ranges).  All variables and  arrays  beginning  with
  4066.              one  of  those  letters  are reset to their pristine
  4067.              state.  If  the  expression  is  omitted,  one-match
  4068.              searches (?pattern?) are reset to match again.  Only
  4069.              resets variables or searches in the current package.
  4070.              Always returns 1.  Examples:
  4071.  
  4072.                  reset 'X';      # reset all X variables
  4073.                  reset 'a-z';    # reset lower case variables
  4074.                  reset;          # just reset ?? searches
  4075.  
  4076.              Note:  resetting  "A-Z"  is  not  recommended  since
  4077.              you'll wipe out your ARGV and ENV arrays.
  4078.  
  4079.              The use of reset on dbm associative arrays does  not
  4080.              change  the  dbm file.  (It does, however, flush any
  4081.              entries cached by perl, which may be useful  if  you
  4082.              are sharing the dbm file.  Then again, maybe not.)
  4083.  
  4084.      return LIST
  4085.              Returns from a subroutine with the value  specified.
  4086.  
  4087.  
  4088.  
  4089. Consensys Computer Inc.                                        62
  4090.  
  4091.  
  4092.  
  4093.  
  4094.  
  4095.  
  4096. PERL(1)                  USER COMMANDS                    PERL(1)
  4097.  
  4098.  
  4099.  
  4100.              (Note that a subroutine can automatically return the
  4101.              value of the last expression evaluated.  That's  the
  4102.              preferred method--use of an explicit _r_e_t_u_r_n is a bit
  4103.              slower.)
  4104.  
  4105.      reverse(LIST)
  4106.  
  4107.      reverse LIST
  4108.              In an array context, returns an array value consist-
  4109.              ing  of  the elements of LIST in the opposite order.
  4110.              In a scalar context, returns a string value consist-
  4111.              ing of the bytes of the first element of LIST in the
  4112.              opposite order.
  4113.  
  4114.      rewinddir(DIRHANDLE)
  4115.  
  4116.      rewinddir DIRHANDLE
  4117.              Sets the current position to the  beginning  of  the
  4118.              directory for the readdir() routine on DIRHANDLE.
  4119.  
  4120.      rindex(STR,SUBSTR,POSITION)
  4121.  
  4122.      rindex(STR,SUBSTR)
  4123.              Works just like index except  that  it  returns  the
  4124.              position  of  the  LAST occurrence of SUBSTR in STR.
  4125.              If  POSITION  is   specified,   returns   the   last
  4126.              occurrence at or before that position.
  4127.  
  4128.      rmdir(FILENAME)
  4129.  
  4130.      rmdir FILENAME
  4131.              Deletes the directory specified by FILENAME if it is
  4132.              empty.   If  it  succeeds it returns 1, otherwise it
  4133.              returns 0 and sets $! (errno).  If FILENAME is omit-
  4134.              ted, uses $_.
  4135.  
  4136.      s/PATTERN/REPLACEMENT/gieo
  4137.              Searches a string  for  a  pattern,  and  if  found,
  4138.              replaces  that pattern with the replacement text and
  4139.              returns the number of substitutions made.  Otherwise
  4140.              it  returns  false (0).  The "g" is optional, and if
  4141.              present, indicates that all occurrences of the  pat-
  4142.              tern  are to be replaced.  The "i" is also optional,
  4143.              and if present, indicates that  matching  is  to  be
  4144.              done in a case-insensitive manner.  The "e" is like-
  4145.              wise optional, and if present,  indicates  that  the
  4146.              replacement  string is to be evaluated as an expres-
  4147.              sion rather than just  as  a  double-quoted  string.
  4148.              Any   non-alphanumeric  delimiter  may  replace  the
  4149.              slashes; if single quotes are used,  no  interpreta-
  4150.              tion is done on the replacement string (the e modif-
  4151.              ier overrides  this,  however);  if  backquotes  are
  4152.  
  4153.  
  4154.  
  4155. Consensys Computer Inc.                                        63
  4156.  
  4157.  
  4158.  
  4159.  
  4160.  
  4161.  
  4162. PERL(1)                  USER COMMANDS                    PERL(1)
  4163.  
  4164.  
  4165.  
  4166.              used, the replacement string is a command to execute
  4167.              whose output will be used as the actual  replacement
  4168.              text.   If  no  string is specified via the =~ or !~
  4169.              operator, the $_ string is  searched  and  modified.
  4170.              (The string specified with =~ must be a scalar vari-
  4171.              able, an array element, or an assignment to  one  of
  4172.              those, i.e. an lvalue.)  If the pattern contains a $
  4173.              that looks like a variable rather  than  an  end-of-
  4174.              string  test, the variable will be interpolated into
  4175.              the pattern at run-time.  If you only want the  pat-
  4176.              tern  compiled  once  the first time the variable is
  4177.              interpolated, add an "o" at the end.  If the PATTERN
  4178.              evaluates to a null string, the most recent success-
  4179.              ful regular expression is used  instead.   See  also
  4180.              the section on regular expressions.  Examples:
  4181.  
  4182.                  s/\bgreen\b/mauve/g;      # don't change wintergreen
  4183.  
  4184.                  $path =~ s|/usr/bin|/usr/local/bin|;
  4185.  
  4186.                  s/Login: $foo/Login: $bar/; # run-time pattern
  4187.  
  4188.                  ($foo = $bar) =~ s/bar/foo/;
  4189.  
  4190.                  $_ = 'abc123xyz';
  4191.                  s/\d+/$&*2/e;        # yields 'abc246xyz'
  4192.                  s/\d+/sprintf("%5d",$&)/e;     # yields 'abc  246xyz'
  4193.                  s/\w/$& x 2/eg;      # yields 'aabbcc  224466xxyyzz'
  4194.  
  4195.                  s/([^ ]*) *([^ ]*)/$2 $1/;     # reverse 1st two fields
  4196.  
  4197.              (Note the use of $ instead of \ in the last example.
  4198.              See section on regular expressions.)
  4199.  
  4200.      scalar(EXPR)
  4201.              Forces EXPR to be interpreted in  a  scalar  context
  4202.              and returns the value of EXPR.
  4203.  
  4204.      seek(FILEHANDLE,POSITION,WHENCE)
  4205.              Randomly positions the file pointer for  FILEHANDLE,
  4206.              just like the fseek() call of stdio.  FILEHANDLE may
  4207.              be an expression whose value gives the name  of  the
  4208.              filehandle.  Returns 1 upon success, 0 otherwise.
  4209.  
  4210.      seekdir(DIRHANDLE,POS)
  4211.              Sets the current position for the readdir()  routine
  4212.              on  DIRHANDLE.   POS  must  be  a  value returned by
  4213.              telldir().  Has  the  same  caveats  about  possible
  4214.              directory  compaction  as  the  corresponding system
  4215.              library routine.
  4216.  
  4217.  
  4218.  
  4219.  
  4220.  
  4221. Consensys Computer Inc.                                        64
  4222.  
  4223.  
  4224.  
  4225.  
  4226.  
  4227.  
  4228. PERL(1)                  USER COMMANDS                    PERL(1)
  4229.  
  4230.  
  4231.  
  4232.      select(FILEHANDLE)
  4233.  
  4234.      select  Returns the currently selected filehandle.  Sets the
  4235.              current default filehandle for output, if FILEHANDLE
  4236.              is supplied.  This has two effects: first,  a  _w_r_i_t_e
  4237.              or a _p_r_i_n_t without a filehandle will default to this
  4238.              FILEHANDLE.  Second, references to variables related
  4239.              to  output  will  refer to this output channel.  For
  4240.              example, if you have to set the top of  form  format
  4241.              for  more  than one output channel, you might do the
  4242.              following:
  4243.  
  4244.                   select(REPORT1);
  4245.                   $^ = 'report1_top';
  4246.                   select(REPORT2);
  4247.                   $^ = 'report2_top';
  4248.              FILEHANDLE may be an expression  whose  value  gives
  4249.              the name of the actual filehandle.  Thus:
  4250.  
  4251.                   $oldfh = select(STDERR); $| = 1; select($oldfh);
  4252.  
  4253.  
  4254.      select(RBITS,WBITS,EBITS,TIMEOUT)
  4255.              This calls the select system call with the  bitmasks
  4256.              specified,  which  can be constructed using fileno()
  4257.              and vec(), along these lines:
  4258.  
  4259.                   $rin = $win = $ein = '';
  4260.                   vec($rin,fileno(STDIN),1) = 1;
  4261.                   vec($win,fileno(STDOUT),1) = 1;
  4262.                   $ein = $rin | $win;
  4263.  
  4264.              If you want to select on many filehandles you  might
  4265.              wish to write a subroutine:
  4266.  
  4267.                   sub fhbits {
  4268.                       local(@fhlist) = split(' ',$_[0]);
  4269.                       local($bits);
  4270.                       for (@fhlist) {
  4271.                        vec($bits,fileno($_),1) = 1;
  4272.                       }
  4273.                       $bits;
  4274.                   }
  4275.                   $rin = &fhbits('STDIN TTY SOCK');
  4276.  
  4277.              The usual idiom is:
  4278.  
  4279.                   ($nfound,$timeleft) =
  4280.                     select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
  4281.  
  4282.              or to block until something becomes ready:
  4283.  
  4284.  
  4285.  
  4286.  
  4287. Consensys Computer Inc.                                        65
  4288.  
  4289.  
  4290.  
  4291.  
  4292.  
  4293.  
  4294. PERL(1)                  USER COMMANDS                    PERL(1)
  4295.  
  4296.  
  4297.  
  4298.                   $nfound = select($rout=$rin, $wout=$win,
  4299.                                  $eout=$ein, undef);
  4300.  
  4301.              Any of the bitmasks can also be undef.  The timeout,
  4302.              if  specified,  is  in  seconds,  which may be frac-
  4303.              tional.  NOTE: not all implementations  are  capable
  4304.              of  returning  the  $timeleft.   If not, they always
  4305.              return $timeleft equal to the supplied $timeout.
  4306.  
  4307.              (The _s_e_l_e_c_t system call is not  implemented  on  MS-
  4308.              DOS.   (The Systerm V semaphore family is not avail-
  4309.              able under MS-DOS.)
  4310.  
  4311.      semctl(ID,SEMNUM,CMD,ARG)
  4312.              Calls the System V IPC function semctl.  If  CMD  is
  4313.              &IPC_STAT  or  &GETALL,  then ARG must be a variable
  4314.              which will hold the returned semid_ds  structure  or
  4315.              semaphore  value  array.   Returns  like  ioctl: the
  4316.              undefined value for error, "0 but true" for zero, or
  4317.              the actual return value otherwise.
  4318.  
  4319.              (Note: the Systerm V semaphore family is not  avail-
  4320.              able under MS-DOS.)
  4321.  
  4322.      semget(KEY,NSEMS,SIZE,FLAGS)
  4323.              Calls the System V IPC function semget.  Returns the
  4324.              semaphore  id, or the undefined value if there is an
  4325.              error.
  4326.  
  4327.      semop(KEY,OPSTRING)
  4328.              Calls the System V IPC  function  semop  to  perform
  4329.              semaphore  operations such as signaling and waiting.
  4330.              OPSTRING must be a packed array of semop structures.
  4331.              Each   semop   structure   can   be  generated  with
  4332.              'pack("sss",  $semnum,  $semop,   $semflag)'.    The
  4333.              number  of  semaphore  operations  is implied by the
  4334.              length of OPSTRING.  Returns true if successful,  or
  4335.              false if there is an error.  As an example, the fol-
  4336.              lowing code waits on semaphore $semnum of  semaphore
  4337.              id $semid:
  4338.  
  4339.                   $semop = pack("sss", $semnum, -1, 0);
  4340.                   die "Semaphore trouble: $!\n" unless semop($semid, $semop);
  4341.  
  4342.              To signal the semaphore, replace "-1" with "1".
  4343.  
  4344.      send(SOCKET,MSG,FLAGS)
  4345.              Sends a message on a socket.  Takes the  same  flags
  4346.              as the system call of the same name.  On unconnected
  4347.              sockets you must specify a destination to  send  TO.
  4348.              Returns  the number of characters sent, or the unde-
  4349.              fined value if there is an error.   Sockets are  not
  4350.  
  4351.  
  4352.  
  4353. Consensys Computer Inc.                                        66
  4354.  
  4355.  
  4356.  
  4357.  
  4358.  
  4359.  
  4360. PERL(1)                  USER COMMANDS                    PERL(1)
  4361.  
  4362.  
  4363.  
  4364.              yet supported on MS-DOS.
  4365.  
  4366.      setpgrp(PID,PGRP)
  4367.              Sets the current process  group  for  the  specified
  4368.              PID,  0  for  the  current  process.  Will produce a
  4369.              fatal error if used on a machine that doesn't imple-
  4370.              ment setpgrp(2).   Not supported on MS-DOS.
  4371.  
  4372.      setpriority(WHICH,WHO,PRIORITY)
  4373.              Sets the current priority for a process,  a  process
  4374.              group,  or a user.  (See setpriority(2).)  Will pro-
  4375.              duce a fatal error if used on a machine that doesn't
  4376.              implement setpriority(2).   Not supported on MS-DOS.
  4377.  
  4378.      setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)
  4379.              Sets the socket option requested.  Returns undefined
  4380.              if  there  is  an error.  OPTVAL may be specified as
  4381.              undef if you don't want to pass an argument.   Sock-
  4382.              ets are not yet supported on MS-DOS.
  4383.  
  4384.      shift(ARRAY)
  4385.  
  4386.      shift ARRAY
  4387.  
  4388.      shift   Shifts the first value of the array off and  returns
  4389.              it,  shortening the array by 1 and moving everything
  4390.              down.  If  there  are  no  elements  in  the  array,
  4391.              returns  the  undefined value.  If ARRAY is omitted,
  4392.              shifts the @ARGV array in the main program, and  the
  4393.              @_  array in subroutines.  (This is determined lexi-
  4394.              cally.)   See  also  unshift(),  push()  and  pop().
  4395.              Shift()  and unshift() do the same thing to the left
  4396.              end of an array that push()  and  pop()  do  to  the
  4397.              right end.
  4398.  
  4399.      shmctl(ID,CMD,ARG)
  4400.              Calls the System V IPC function shmctl.  If  CMD  is
  4401.              &IPC_STAT,  then  ARG  must be a variable which will
  4402.              hold the returned shmid_ds structure.  Returns  like
  4403.              ioctl:  the  undefined value for error, "0 but true"
  4404.              for zero, or  the  actual  return  value  otherwise.
  4405.              (The  shared  memory  family  is not available under
  4406.              MS-DOS.)
  4407.  
  4408.      shmget(KEY,SIZE,FLAGS)
  4409.              Calls the System V IPC function shmget.  Returns the
  4410.              shared  memory segment id, or the undefined value if
  4411.              there is an error.
  4412.  
  4413.      shmread(ID,VAR,POS,SIZE)
  4414.  
  4415.  
  4416.  
  4417.  
  4418.  
  4419. Consensys Computer Inc.                                        67
  4420.  
  4421.  
  4422.  
  4423.  
  4424.  
  4425.  
  4426. PERL(1)                  USER COMMANDS                    PERL(1)
  4427.  
  4428.  
  4429.  
  4430.      shmwrite(ID,STRING,POS,SIZE)
  4431.              Reads or writes the System V shared  memory  segment
  4432.              ID starting at position POS for size SIZE by attach-
  4433.              ing to it, copying in/out, and  detaching  from  it.
  4434.              When reading, VAR must be a variable which will hold
  4435.              the data read.  When writing, if STRING is too long,
  4436.              only  SIZE  bytes  are used; if STRING is too short,
  4437.              nulls are written to fill out  SIZE  bytes.   Return
  4438.              true if successful, or false if there is an error.
  4439.  
  4440.      shutdown(SOCKET,HOW)
  4441.              Shuts down a socket connection in the  manner  indi-
  4442.              cated  by  HOW, which has the same interpretation as
  4443.              in the system call of the same name.   (Sockets  are
  4444.              not yet supported on MS-DOS.)
  4445.  
  4446.      sin(EXPR)
  4447.  
  4448.      sin EXPR
  4449.              Returns the sine of EXPR (expressed in radians).  If
  4450.              EXPR is omitted, returns sine of $_.
  4451.  
  4452.      sleep(EXPR)
  4453.  
  4454.      sleep EXPR
  4455.  
  4456.      sleep   Causes the script to sleep for EXPR seconds, or for-
  4457.              ever  if no EXPR.  May be interrupted by sending the
  4458.              process a SIGALRM.  Returns the  number  of  seconds
  4459.              actually slept.  You probably cannot mix alarm() and
  4460.              sleep() calls, since sleep()  is  often  implemented
  4461.              using  alarm().   ! .if !'both'unix' ! Pretty worth-
  4462.              less on MS-DOS, as it  just  wastes  the  number  of
  4463.              seconds ! requested.  !
  4464.  
  4465.      socket(SOCKET,DOMAIN,TYPE,PROTOCOL)
  4466.              Opens a socket of the specified kind and attaches it
  4467.              to filehandle SOCKET.  DOMAIN, TYPE and PROTOCOL are
  4468.              specified the same as for the  system  call  of  the
  4469.              same name.  You may need to run h2ph on sys/socket.h
  4470.              to get the proper values handy  in  a  perl  library
  4471.              file.   Return  true if successful.  See the example
  4472.              in the  section  on  Interprocess  Communication.
  4473.              Sockets are not yet supported on MS-DOS.
  4474.  
  4475.      socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)
  4476.              Creates an unnamed pair of sockets in the  specified
  4477.              domain,  of  the  specified  type.  DOMAIN, TYPE and
  4478.              PROTOCOL are specified the same as  for  the  system
  4479.              call  of  the same name.  If unimplemented, yields a
  4480.              fatal error.  Return true if successful.     Sockets
  4481.              are not yet supported on MS-DOS.
  4482.  
  4483.  
  4484.  
  4485. Consensys Computer Inc.                                        68
  4486.  
  4487.  
  4488.  
  4489.  
  4490.  
  4491.  
  4492. PERL(1)                  USER COMMANDS                    PERL(1)
  4493.  
  4494.  
  4495.  
  4496.      sort(SUBROUTINE LIST)
  4497.  
  4498.      sort(LIST)
  4499.  
  4500.      sort SUBROUTINE LIST
  4501.  
  4502.      sort BLOCK LIST
  4503.  
  4504.      sort LIST
  4505.              Sorts the LIST and returns the sorted  array  value.
  4506.              Nonexistent  values  of arrays are stripped out.  If
  4507.              SUBROUTINE or BLOCK is omitted,  sorts  in  standard
  4508.              string  comparison  order.   If SUBROUTINE is speci-
  4509.              fied, gives the name of a subroutine that returns an
  4510.              integer  less  than,  equal  to,  or greater than 0,
  4511.              depending on how the elements of the array are to be
  4512.              ordered.   (The  <=> and cmp operators are extremely
  4513.              useful in  such  routines.)   SUBROUTINE  may  be  a
  4514.              scalar  variable  name, in which case the value pro-
  4515.              vides the name of the subroutine to use.   In  place
  4516.              of  a SUBROUTINE name, you can provide a BLOCK as an
  4517.              anonymous, in-line sort subroutine.
  4518.  
  4519.              In the interests of efficiency  the  normal  calling
  4520.              code for subroutines is bypassed, with the following
  4521.              effects: the subroutine may not be a recursive  sub-
  4522.              routine,  and  the  two  elements to be compared are
  4523.              passed into the subroutine not via @_ but as $a  and
  4524.              $b  (see  example below).  They are passed by refer-
  4525.              ence so don't modify $a and $b.
  4526.  
  4527.              Examples:
  4528.  
  4529.                   # sort lexically
  4530.                   @articles = sort @files;
  4531.  
  4532.                   # same thing, but with explicit sort routine
  4533.                   @articles = sort {$a cmp $b;} @files;
  4534.  
  4535.                   # same thing in reversed order
  4536.                   @articles = sort {$b cmp $a;} @files;
  4537.  
  4538.                   # sort numerically ascending
  4539.                   @articles = sort {$a <=> $b;} @files;
  4540.  
  4541.                   # sort numerically descending
  4542.                   @articles = sort {$b <=> $a;} @files;
  4543.  
  4544.  
  4545.  
  4546.  
  4547.  
  4548.  
  4549.  
  4550.  
  4551. Consensys Computer Inc.                                        69
  4552.  
  4553.  
  4554.  
  4555.  
  4556.  
  4557.  
  4558. PERL(1)                  USER COMMANDS                    PERL(1)
  4559.  
  4560.  
  4561.  
  4562.                   # sort using explicit subroutine name
  4563.                   sub byage {
  4564.                       $age{$a} <=> $age{$b};    # presuming integers
  4565.                   }
  4566.                   @sortedclass = sort byage @class;
  4567.  
  4568.                   sub reverse { $b cmp $a; }
  4569.                   @harry = ('dog','cat','x','Cain','Abel');
  4570.                   @george = ('gone','chased','yz','Punished','Axed');
  4571.                   print sort @harry;
  4572.                        # prints AbelCaincatdogx
  4573.                   print sort reverse @harry;
  4574.                        # prints xdogcatCainAbel
  4575.                   print sort @george, 'to', @harry;
  4576.                        # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
  4577.  
  4578.  
  4579.      splice(ARRAY,OFFSET,LENGTH,LIST)
  4580.  
  4581.      splice(ARRAY,OFFSET,LENGTH)
  4582.  
  4583.      splice(ARRAY,OFFSET)
  4584.              Removes the elements designated by OFFSET and LENGTH
  4585.              from  an  array, and replaces them with the elements
  4586.              of LIST, if any.  Returns the elements removed  from
  4587.              the array.  The array grows or shrinks as necessary.
  4588.              If LENGTH is omitted, removes everything from OFFSET
  4589.              onward.   The following equivalencies hold (assuming
  4590.              $[ == 0):
  4591.  
  4592.                   push(@a,$x,$y)                splice(@a,$#a+1,0,$x,$y)
  4593.                   pop(@a)                       splice(@a,-1)
  4594.                   shift(@a)                     splice(@a,0,1)
  4595.                   unshift(@a,$x,$y)             splice(@a,0,0,$x,$y)
  4596.                   $a[$x] = $y                   splice(@a,$x,1,$y);
  4597.  
  4598.              Example, assuming array lengths are passed before arrays:
  4599.  
  4600.                   sub aeq { # compare two array values
  4601.                        local(@a) = splice(@_,0,shift);
  4602.                        local(@b) = splice(@_,0,shift);
  4603.                        return 0 unless @a == @b;     # same len?
  4604.                        while (@a) {
  4605.                            return 0 if pop(@a) ne pop(@b);
  4606.                        }
  4607.                        return 1;
  4608.                   }
  4609.                   if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
  4610.  
  4611.  
  4612.  
  4613.  
  4614.  
  4615.  
  4616.  
  4617. Consensys Computer Inc.                                        70
  4618.  
  4619.  
  4620.  
  4621.  
  4622.  
  4623.  
  4624. PERL(1)                  USER COMMANDS                    PERL(1)
  4625.  
  4626.  
  4627.  
  4628.      split(/PATTERN/,EXPR,LIMIT)
  4629.  
  4630.      split(/PATTERN/,EXPR)
  4631.  
  4632.      split(/PATTERN/)
  4633.  
  4634.      split   Splits a  string  into  an  array  of  strings,  and
  4635.              returns  it.   (If  not in an array context, returns
  4636.              the number of fields found and splits  into  the  @_
  4637.              array.   (In  an  array  context,  you can force the
  4638.              split into @_ by using ?? as the pattern delimiters,
  4639.              but  it still returns the array value.))  If EXPR is
  4640.              omitted, splits the $_ string.  If PATTERN  is  also
  4641.              omitted,  splits  on  whitespace (/[ \t\n]+/).  Any-
  4642.              thing matching PATTERN is taken to  be  a  delimiter
  4643.              separating the fields.  (Note that the delimiter may
  4644.              be longer than one character.)  If LIMIT  is  speci-
  4645.              fied,  splits  into  no  more  than that many fields
  4646.              (though it may  split  into  fewer).   If  LIMIT  is
  4647.              unspecified,   trailing  null  fields  are  stripped
  4648.              (which potential users of pop()  would  do  well  to
  4649.              remember).   A pattern matching the null string (not
  4650.              to be confused with a null pattern //, which is just
  4651.              one  member  of  the set of patterns matching a null
  4652.              string) will split the value of EXPR  into  separate
  4653.              characters  at  each point it matches that way.  For
  4654.              example:
  4655.  
  4656.                   print join(':', split(/ */, 'hi there'));
  4657.  
  4658.              produces the output 'h:i:t:h:e:r:e'.
  4659.  
  4660.              The LIMIT parameter can be used to partially split a
  4661.              line
  4662.  
  4663.                   ($login, $passwd, $remainder) = split(/:/, $_, 3);
  4664.  
  4665.              (When assigning to a list, if LIMIT is omitted, perl
  4666.              supplies a LIMIT one larger than the number of vari-
  4667.              ables in the list, to avoid unnecessary  work.   For
  4668.              the  list  above LIMIT would have been 4 by default.
  4669.              In time critical applications it behooves you not to
  4670.              split into more fields than you really need.)
  4671.  
  4672.              If  the  PATTERN  contains  parentheses,  additional
  4673.              array  elements  are created from each matching sub-
  4674.              string in the delimiter.
  4675.  
  4676.                   split(/([,-])/,"1-10,20");
  4677.  
  4678.              produces the array value
  4679.  
  4680.  
  4681.  
  4682.  
  4683. Consensys Computer Inc.                                        71
  4684.  
  4685.  
  4686.  
  4687.  
  4688.  
  4689.  
  4690. PERL(1)                  USER COMMANDS                    PERL(1)
  4691.  
  4692.  
  4693.  
  4694.                   (1,'-',10,',',20)
  4695.  
  4696.              The  pattern  /PATTERN/  may  be  replaced  with  an
  4697.              expression to specify patterns that vary at runtime.
  4698.              (To  do   runtime   compilation   only   once,   use
  4699.              /$variable/o.)   As  a  special  case,  specifying a
  4700.              space (' ') will split on white space just as  split
  4701.              with no arguments does, but leading white space does
  4702.              NOT produce a null first  field.   Thus,  split(' ')
  4703.              can  be  used  to  emulate  _a_w_k's  default behavior,
  4704.              whereas split(/ /) will give you as many  null  ini-
  4705.              tial fields as there are leading spaces.
  4706.  
  4707.              Example:
  4708.  
  4709.                   open(passwd, '/etc/passwd');
  4710.                   while (<passwd>) {
  4711.                        ($login, $passwd, $uid, $gid, $gcos, $home, $shell)
  4712.                             = split(/:/);
  4713.                        ...
  4714.                   }
  4715.  
  4716.              (Note that $shell above will still have a newline on
  4717.              it.  See chop().)  See also _j_o_i_n.
  4718.  
  4719.      sprintf(FORMAT,LIST)
  4720.              Returns a string formatted by the usual printf  con-
  4721.              ventions.  The * character is not supported.
  4722.  
  4723.      sqrt(EXPR)
  4724.  
  4725.      sqrt EXPR
  4726.              Return the square root of EXPR.  If EXPR is omitted,
  4727.              returns square root of $_.
  4728.  
  4729.      srand(EXPR)
  4730.  
  4731.      srand EXPR
  4732.              Sets the random number seed for the  _r_a_n_d  operator.
  4733.              If EXPR is omitted, does srand(time).
  4734.  
  4735.      stat(FILEHANDLE)
  4736.  
  4737.      stat FILEHANDLE
  4738.  
  4739.      stat(EXPR)
  4740.  
  4741.      stat SCALARVARIABLE
  4742.              Returns a 13-element array giving the statistics for
  4743.              a  file,  either  the file opened via FILEHANDLE, or
  4744.              named by EXPR.  Typically used as follows:
  4745.  
  4746.  
  4747.  
  4748.  
  4749. Consensys Computer Inc.                                        72
  4750.  
  4751.  
  4752.  
  4753.  
  4754.  
  4755.  
  4756. PERL(1)                  USER COMMANDS                    PERL(1)
  4757.  
  4758.  
  4759.  
  4760.                  ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
  4761.                     $atime,$mtime,$ctime,$blksize,$blocks)
  4762.                         = stat($filename);
  4763.  
  4764.              If stat is passed the special filehandle  consisting
  4765.              of  an  underline,  no stat is done, but the current
  4766.              contents of the stat structure from the last stat or
  4767.              filetest are returned.  (Note that on MS-DOS several
  4768.              of these values are spurious.)   Example:
  4769.  
  4770.                   if (-x $file && (($d) = stat(_)) && $d < 0) {
  4771.                        print "$file is executable NFS file\n";
  4772.                   }
  4773.  
  4774.              (This only works on machines for  which  the  device
  4775.              number is negative under NFS.)
  4776.  
  4777.      study(SCALAR)
  4778.  
  4779.      study SCALAR
  4780.  
  4781.      study   Takes extra time to study SCALAR ($_ if unspecified)
  4782.              in anticipation of doing many pattern matches on the
  4783.              string before it is next modified.  This may or  may
  4784.              not save time, depending on the nature and number of
  4785.              patterns you are searching on, and on the  distribu-
  4786.              tion  of  character  frequencies in the string to be
  4787.              searched--you probably want to compare runtimes with
  4788.              and  without  it  to  see  which runs faster.  Those
  4789.              loops which scan for  many  short  constant  strings
  4790.              (including  the  constant parts of more complex pat-
  4791.              terns) will benefit most.  You  may  have  only  one
  4792.              study  active  at  a  time--if you study a different
  4793.              scalar the first is  "unstudied".   (The  way  study
  4794.              works  is  this: a linked list of every character in
  4795.              the string to be searched is made, so we  know,  for
  4796.              example,  where  all  the  'k' characters are.  From
  4797.              each  search  string,  the   rarest   character   is
  4798.              selected, based on some static frequency tables con-
  4799.              structed from some  C  programs  and  English  text.
  4800.              Only those places that contain this "rarest" charac-
  4801.              ter are examined.)
  4802.  
  4803.              For example, here is a loop which inserts index pro-
  4804.              ducing  entries before any line containing a certain
  4805.              pattern:
  4806.  
  4807.  
  4808.  
  4809.  
  4810.  
  4811.  
  4812.  
  4813.  
  4814.  
  4815. Consensys Computer Inc.                                        73
  4816.  
  4817.  
  4818.  
  4819.  
  4820.  
  4821.  
  4822. PERL(1)                  USER COMMANDS                    PERL(1)
  4823.  
  4824.  
  4825.  
  4826.                   while (<>) {
  4827.                        study;
  4828.                        print ".IX foo\n" if /\bfoo\b/;
  4829.                        print ".IX bar\n" if /\bbar\b/;
  4830.                        print ".IX blurfl\n" if /\bblurfl\b/;
  4831.                        ...
  4832.                        print;
  4833.                   }
  4834.  
  4835.              In searching for /\bfoo\b/, only those locations  in
  4836.              $_  that  contain 'f' will be looked at, because 'f'
  4837.              is rarer than 'o'.  In general, this is  a  big  win
  4838.              except  in pathological cases.  The only question is
  4839.              whether it saves you more time than it took to build
  4840.              the linked list in the first place.
  4841.  
  4842.              Note that if you have to look for strings  that  you
  4843.              don't  know  till  runtime,  you can build an entire
  4844.              loop as a string and eval that to avoid  recompiling
  4845.              all your patterns all the time.  Together with unde-
  4846.              fining $/ to input entire files as one record,  this
  4847.              can be very fast, often faster than specialized pro-
  4848.              grams like fgrep.  The following  scans  a  list  of
  4849.              files  (@files)  for  a  list of words (@words), and
  4850.              prints out the names of those files that  contain  a
  4851.              match:
  4852.  
  4853.                   $search = 'while (<>) { study;';
  4854.                   foreach $word (@words) {
  4855.                       $search .= "++\$seen{\$ARGV} if /\b$word\b/;\n";
  4856.                   }
  4857.                   $search .= "}";
  4858.                   @ARGV = @files;
  4859.                   undef $/;
  4860.                   eval $search;       # this screams
  4861.                   $/ = "\n";          # put back to normal input delim
  4862.                   foreach $file (sort keys(%seen)) {
  4863.                       print $file, "\n";
  4864.                   }
  4865.  
  4866.  
  4867.      substr(EXPR,OFFSET,LEN)
  4868.  
  4869.      substr(EXPR,OFFSET)
  4870.              Extracts a substring out of  EXPR  and  returns  it.
  4871.              First  character  is at offset 0, or whatever you've
  4872.              set $[ to.  If OFFSET is negative, starts  that  far
  4873.              from  the  end  of  the  string.  If LEN is omitted,
  4874.              returns everything to the end of  the  string.   You
  4875.              can use the substr() function as an lvalue, in which
  4876.              case EXPR must be an lvalue.  If  you  assign  some-
  4877.              thing  shorter than LEN, the string will shrink, and
  4878.  
  4879.  
  4880.  
  4881. Consensys Computer Inc.                                        74
  4882.  
  4883.  
  4884.  
  4885.  
  4886.  
  4887.  
  4888. PERL(1)                  USER COMMANDS                    PERL(1)
  4889.  
  4890.  
  4891.  
  4892.              if you assign something longer than LEN, the  string
  4893.              will grow to accommodate it.  To keep the string the
  4894.              same length you may need to pad or chop  your  value
  4895.              using sprintf().
  4896.  
  4897.      symlink(OLDFILE,NEWFILE)
  4898.              Creates a new filename symbolically  linked  to  the
  4899.              old  filename.   (Note  that MS-DOS does not support
  4900.              symbolic links.)  Returns 1 for  success,  0  other-
  4901.              wise.  On systems that don't support symbolic links,
  4902.              produces a fatal error at run time.   To  check  for
  4903.              that, use eval:
  4904.  
  4905.                   $symlink_exists = (eval 'symlink("","");', $@ eq '');
  4906.  
  4907.  
  4908.  
  4909.      syscall(LIST)
  4910.  
  4911.      syscall LIST
  4912.              Calls the system call specified as the first element
  4913.              of the list, passing the remaining elements as argu-
  4914.              ments to the system call.  If unimplemented, and  on
  4915.              MS-DOS,  produces  a fatal error.  The arguments are
  4916.              interpreted as  follows:  if  a  given  argument  is
  4917.              numeric,  the argument is passed as an int.  If not,
  4918.              the pointer to the string value is passed.  You  are
  4919.              responsible  to  make  sure a string is pre-extended
  4920.              long enough to receive  any  result  that  might  be
  4921.              written  into  a  string.  If your integer arguments
  4922.              are not literals and have never been interpreted  in
  4923.              a  numeric context, you may need to add 0 to them to
  4924.              force them to look like numbers.
  4925.  
  4926.                   require 'syscall.ph';         # may need to run h2ph
  4927.                   syscall(&SYS_write, fileno(STDOUT), "hi there\n", 9);
  4928.  
  4929.  
  4930.  
  4931.      sysread(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  4932.  
  4933.      sysread(FILEHANDLE,SCALAR,LENGTH)
  4934.              Attempts to read LENGTH bytes of data into  variable
  4935.              SCALAR from the specified FILEHANDLE, using the sys-
  4936.              tem call read(2).  It bypasses stdio, so mixing this
  4937.              with  other  kinds  of  reads  may  cause confusion.
  4938.              Returns the number of bytes actually read, or  undef
  4939.              if  there  was  an  error.   SCALAR will be grown or
  4940.              shrunk to the length actually read.  An  OFFSET  may
  4941.              be  specified  to  place the read data at some other
  4942.              place than the beginning of the string.
  4943.  
  4944.  
  4945.  
  4946.  
  4947. Consensys Computer Inc.                                        75
  4948.  
  4949.  
  4950.  
  4951.  
  4952.  
  4953.  
  4954. PERL(1)                  USER COMMANDS                    PERL(1)
  4955.  
  4956.  
  4957.  
  4958.      system(LIST)
  4959.  
  4960.      system LIST
  4961.              Does exactly the same thing as  "exec  LIST"  except
  4962.              that  a  fork  is done first, and the parent process
  4963.              waits for the child process to complete.  Note  that
  4964.              argument  processing  varies depending on the number
  4965.              of arguments.  The return value is the  exit  status
  4966.              of  the  program as returned by the wait() call.  To
  4967.              get the actual exit value divide by 256.   See  also
  4968.              _e_x_e_c.
  4969.  
  4970.              On MS-DOS, this is implemented using the _s_p_a_w_n  sys-
  4971.              tem call.
  4972.  
  4973.      syswrite(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  4974.  
  4975.      syswrite(FILEHANDLE,SCALAR,LENGTH)
  4976.              Attempts to write LENGTH bytes of data from variable
  4977.              SCALAR to the specified FILEHANDLE, using the system
  4978.              call write(2).  It bypasses stdio,  so  mixing  this
  4979.              with prints may cause confusion.  Returns the number
  4980.              of bytes actually written, or undef if there was  an
  4981.              error.  An OFFSET may be specified to place the read
  4982.              data at some other place than the beginning  of  the
  4983.              string.
  4984.  
  4985.      tell(FILEHANDLE)
  4986.  
  4987.      tell FILEHANDLE
  4988.  
  4989.      tell    Returns the current file  position  for  FILEHANDLE.
  4990.              FILEHANDLE  may  be  an expression whose value gives
  4991.              the name of the actual filehandle.  If FILEHANDLE is
  4992.              omitted, assumes the file last read.
  4993.  
  4994.      telldir(DIRHANDLE)
  4995.  
  4996.      telldir DIRHANDLE
  4997.              Returns the current position of the  readdir()  rou-
  4998.              tines on DIRHANDLE.  Value may be given to seekdir()
  4999.              to access a particular location in a directory.  Has
  5000.              the same caveats about possible directory compaction
  5001.              as the corresponding system library routine.
  5002.  
  5003.      time    Returns  the  number  of  non-leap   seconds   since
  5004.              00:00:00 UTC, January 1, 1970.  Suitable for feeding
  5005.              to gmtime() and localtime().
  5006.  
  5007.      times   Returns a four-element array  giving  the  user  and
  5008.              system  times,  in seconds, for this process and the
  5009.              children of this process.  Not supported on MS-DOS.
  5010.  
  5011.  
  5012.  
  5013. Consensys Computer Inc.                                        76
  5014.  
  5015.  
  5016.  
  5017.  
  5018.  
  5019.  
  5020. PERL(1)                  USER COMMANDS                    PERL(1)
  5021.  
  5022.  
  5023.  
  5024.                  ($user,$system,$cuser,$csystem) = times;
  5025.  
  5026.  
  5027.  
  5028.      tr/SEARCHLIST/REPLACEMENTLIST/cds
  5029.  
  5030.      y/SEARCHLIST/REPLACEMENTLIST/cds
  5031.              Translates all occurrences of the  characters  found
  5032.              in  the search list with the corresponding character
  5033.              in the replacement list.  It returns the  number  of
  5034.              characters  replaced  or  deleted.   If no string is
  5035.              specified via the =~ or !~ operator, the  $_  string
  5036.              is  translated.   (The string specified with =~ must
  5037.              be a  scalar  variable,  an  array  element,  or  an
  5038.              assignment  to  one  of those, i.e. an lvalue.)  For
  5039.              _s_e_d devotees, _y is provided as a synonym for _t_r.
  5040.  
  5041.              If the c modifier is specified, the SEARCHLIST char-
  5042.              acter  set  is  complemented.   If the d modifier is
  5043.              specified, any characters  specified  by  SEARCHLIST
  5044.              that  are  not found in REPLACEMENTLIST are deleted.
  5045.              (Note that this is slightly more flexible  than  the
  5046.              behavior  of some _t_r programs, which delete anything
  5047.              they find in the  SEARCHLIST,  period.)   If  the  s
  5048.              modifier  is specified, sequences of characters that
  5049.              were translated to the same character  are  squashed
  5050.              down to 1 instance of the character.
  5051.  
  5052.              If the d modifier was used, the  REPLACEMENTLIST  is
  5053.              always interpreted exactly as specified.  Otherwise,
  5054.              if the REPLACEMENTLIST is  shorter  than  the  SEAR-
  5055.              CHLIST, the final character is replicated till it is
  5056.              long enough.  If the REPLACEMENTLIST  is  null,  the
  5057.              SEARCHLIST is replicated.  This latter is useful for
  5058.              counting characters in a  class,  or  for  squashing
  5059.              character sequences in a class.
  5060.  
  5061.              Examples:
  5062.  
  5063.                  $ARGV[1] =~ y/A-Z/a-z/;   # canonicalize to lower case
  5064.  
  5065.                  $cnt = tr/*/*/;           # count the stars in $_
  5066.  
  5067.                  $cnt = tr/0-9//;          # count the digits in $_
  5068.  
  5069.                  tr/a-zA-Z//s;             # bookkeeper -> bokeper
  5070.  
  5071.                  ($HOST = $host) =~ tr/a-z/A-Z/;
  5072.  
  5073.                  y/a-zA-Z/ /cs;            # change non-alphas to single space
  5074.  
  5075.                  tr/\200-\377/\0-\177/;    # delete 8th bit
  5076.  
  5077.  
  5078.  
  5079. Consensys Computer Inc.                                        77
  5080.  
  5081.  
  5082.  
  5083.  
  5084.  
  5085.  
  5086. PERL(1)                  USER COMMANDS                    PERL(1)
  5087.  
  5088.  
  5089.  
  5090.      truncate(FILEHANDLE,LENGTH)
  5091.  
  5092.      truncate(EXPR,LENGTH)
  5093.              Truncates the file opened on FILEHANDLE, or named by
  5094.              EXPR,  to  the  specified  length.  Produces a fatal
  5095.              error if truncate isn't implemented on your system.
  5096.  
  5097.      umask(EXPR)
  5098.  
  5099.      umask EXPR
  5100.  
  5101.      umask   Sets the umask for the process and returns  the  old
  5102.              one.   If  EXPR  is  omitted, merely returns current
  5103.              umask.  Not supported on MS-DOS.
  5104.  
  5105.      undef(EXPR)
  5106.  
  5107.      undef EXPR
  5108.  
  5109.      undef   Undefines the  value  of  EXPR,  which  must  be  an
  5110.              lvalue.   Use  only  on  a  scalar  value, an entire
  5111.              array, or a subroutine name (using &).  (Undef  will
  5112.              probably  not  do what you expect on most predefined
  5113.              variables or dbm array values.)  Always returns  the
  5114.              undefined  value.   You  can omit the EXPR, in which
  5115.              case nothing is undefined,  but  you  still  get  an
  5116.              undefined value that you could, for instance, return
  5117.              from a subroutine.  Examples:
  5118.  
  5119.                   undef $foo;
  5120.                   undef $bar{'blurfl'};
  5121.                   undef @ary;
  5122.                   undef %assoc;
  5123.                   undef &mysub;
  5124.                   return (wantarray ? () : undef) if $they_blew_it;
  5125.  
  5126.  
  5127.      unlink(LIST)
  5128.  
  5129.      unlink LIST
  5130.              Deletes a list of  files.   Returns  the  number  of
  5131.              files  successfully  deleted.   (MS-DOS users should
  5132.              note that open files cannot be deleted.)
  5133.  
  5134.                   $cnt = unlink 'a', 'b', 'c';
  5135.                   unlink @goners;
  5136.                   unlink <*.bak>;
  5137.  
  5138.              Note: unlink will not delete directories unless  you
  5139.              are  superuser  and the ----UUUU flag is supplied to _p_e_r_l.
  5140.              Even if these conditions are  met,  be  warned  that
  5141.              unlinking  a  directory  can  inflict damage on your
  5142.  
  5143.  
  5144.  
  5145. Consensys Computer Inc.                                        78
  5146.  
  5147.  
  5148.  
  5149.  
  5150.  
  5151.  
  5152. PERL(1)                  USER COMMANDS                    PERL(1)
  5153.  
  5154.  
  5155.  
  5156.              filesystem.  Use rmdir instead.   (MS-DOS  does  not
  5157.              support directory unlinking: use rmdir.)
  5158.  
  5159.      unpack(TEMPLATE,EXPR)
  5160.              Unpack does the reverse of pack: it takes  a  string
  5161.              representing  a structure and expands it out into an
  5162.              array value,  returning  the  array  value.   (In  a
  5163.              scalar  context,  it  merely returns the first value
  5164.              produced.)  The TEMPLATE has the same format  as  in
  5165.              the  pack  function.   Here's a subroutine that does
  5166.              substring:
  5167.  
  5168.                   sub substr {
  5169.                        local($what,$where,$howmuch) = @_;
  5170.                        unpack("x$where a$howmuch", $what);
  5171.                   }
  5172.  
  5173.              and then there's
  5174.  
  5175.                   sub ord { unpack("c",$_[0]); }
  5176.  
  5177.              In addition, you may prefix a field with a %<number>
  5178.              to indicate that you want a <number>-bit checksum of
  5179.              the items instead of the items themselves.   Default
  5180.              is  a  16-bit  checksum.  For example, the following
  5181.              computes the same number as the System  V  sum  pro-
  5182.              gram:
  5183.  
  5184.                   while (<>) {
  5185.                       $checksum += unpack("%16C*", $_);
  5186.                   }
  5187.                   $checksum %= 65536;
  5188.  
  5189.  
  5190.      unshift(ARRAY,LIST)
  5191.              Does the opposite of a _s_h_i_f_t.  Or the opposite of  a
  5192.              _p_u_s_h,  depending  on  how  you look at it.  Prepends
  5193.              list to the front of  the  array,  and  returns  the
  5194.              number of elements in the new array.
  5195.  
  5196.                   unshift(ARGV, '-e') unless $ARGV[0] =~ /^-/;
  5197.  
  5198.  
  5199.      utime(LIST)
  5200.  
  5201.      utime LIST
  5202.              Changes the access and modification  times  on  each
  5203.              file  of a list of files.  The first two elements of
  5204.              the list must be the NUMERICAL access and  modifica-
  5205.              tion  times,  in that order.  (On MS-DOS, the access
  5206.              time field is ignored.)  Returns the number of files
  5207.              successfully  changed.   The inode modification time
  5208.  
  5209.  
  5210.  
  5211. Consensys Computer Inc.                                        79
  5212.  
  5213.  
  5214.  
  5215.  
  5216.  
  5217.  
  5218. PERL(1)                  USER COMMANDS                    PERL(1)
  5219.  
  5220.  
  5221.  
  5222.              of each file is set to the current time.  Example of
  5223.              a "touch" command:
  5224.  
  5225.                   #!/usr/bin/perl
  5226.                   $now = time;
  5227.                   utime $now, $now, @ARGV;
  5228.  
  5229.  
  5230.      values(ASSOC_ARRAY)
  5231.  
  5232.      values ASSOC_ARRAY
  5233.              Returns a normal array consisting of all the  values
  5234.              of  the  named  associative  array.   The values are
  5235.              returned in an apparently random order,  but  it  is
  5236.              the  same order as either the keys() or each() func-
  5237.              tion would produce on  the  same  array.   See  also
  5238.              keys() and each().
  5239.  
  5240.      vec(EXPR,OFFSET,BITS)
  5241.              Treats a string as a vector  of  unsigned  integers,
  5242.              and  returns  the  value  of the bitfield specified.
  5243.              May also be assigned to.  BITS must be  a  power  of
  5244.              two from 1 to 32.
  5245.  
  5246.              Vectors created with vec() can also  be  manipulated
  5247.              with  the  logical  operators |, & and ^, which will
  5248.              assume a bit vector operation is desired  when  both
  5249.              operands  are  strings.   This interpretation is not
  5250.              enabled unless there is at least one vec()  in  your
  5251.              program, to protect older programs.
  5252.  
  5253.              To transform a bit vector into a string or array  of
  5254.              0's and 1's, use these:
  5255.  
  5256.                   $bits = unpack("b*", $vector);
  5257.                   @bits = split(//, unpack("b*", $vector));
  5258.  
  5259.              If you know the exact length in bits, it can be used
  5260.              in place of the *.
  5261.  
  5262.      wait    Waits for a child process to terminate  and  returns
  5263.              the  pid of the deceased process, or -1 if there are
  5264.              no child processes.  The status is returned in $?.
  5265.  
  5266.              Not supported on MS-DOS:  subprocesses  are  run  to
  5267.              completion  and  their  status is returned by _c_l_o_s_e,
  5268.              _s_y_s_t_e_m, or ``.
  5269.  
  5270.  
  5271.  
  5272.  
  5273.  
  5274.  
  5275.  
  5276.  
  5277. Consensys Computer Inc.                                        80
  5278.  
  5279.  
  5280.  
  5281.  
  5282.  
  5283.  
  5284. PERL(1)                  USER COMMANDS                    PERL(1)
  5285.  
  5286.  
  5287.  
  5288.      waitpid(PID,FLAGS)
  5289.              Waits for a particular child  process  to  terminate
  5290.              and  returns  the pid of the deceased process, or -1
  5291.              if there is no such child process.  Not supported on
  5292.              MS-DOS.  The status is returned in $?.  If you say
  5293.  
  5294.                   require "sys/wait.h";
  5295.                   ...
  5296.                   waitpid(-1,&WNOHANG);
  5297.  
  5298.              then you can do a non-blocking wait for any process.
  5299.              Non-blocking wait is only available on machines sup-
  5300.              porting either the _w_a_i_t_p_i_d (_2) or _w_a_i_t_4  (_2)  system
  5301.              calls.   However,  waiting for a particular pid with
  5302.              FLAGS of 0 is implemented  everywhere.   (Perl  emu-
  5303.              lates  the  system  call  by  remembering the status
  5304.              values of processes that have exited  but  have  not
  5305.              been harvested by the Perl script yet.)
  5306.  
  5307.      wantarray
  5308.              Returns true if the context of the currently execut-
  5309.              ing  subroutine  is  looking  for  an  array  value.
  5310.              Returns false  if  the  context  is  looking  for  a
  5311.              scalar.
  5312.  
  5313.                   return wantarray ? () : undef;
  5314.  
  5315.  
  5316.      warn(LIST)
  5317.  
  5318.      warn LIST
  5319.              Produces a message on STDERR just  like  "die",  but
  5320.              doesn't exit.
  5321.  
  5322.      write(FILEHANDLE)
  5323.  
  5324.      write(EXPR)
  5325.  
  5326.      write   Writes a formatted record (possibly  multi-line)  to
  5327.              the specified file, using the format associated with
  5328.              that file.  By default the format for a file is  the
  5329.              one  having the same name is the filehandle, but the
  5330.              format for the current output channel  (see  _s_e_l_e_c_t)
  5331.              may  be  set explicitly by assigning the name of the
  5332.              format to the $~ variable.
  5333.  
  5334.              Top of form processing is handled automatically:  if
  5335.              there  is  insufficient room on the current page for
  5336.              the formatted record, the page is advanced by  writ-
  5337.              ing  a  form  feed,  a special top-of-page format is
  5338.              used to format the new page  header,  and  then  the
  5339.              record  is  written.   By  default  the  top-of-page
  5340.  
  5341.  
  5342.  
  5343. Consensys Computer Inc.                                        81
  5344.  
  5345.  
  5346.  
  5347.  
  5348.  
  5349.  
  5350. PERL(1)                  USER COMMANDS                    PERL(1)
  5351.  
  5352.  
  5353.  
  5354.              format is the name of  the  filehandle  with  "_TOP"
  5355.              appended, but it may be dynamicallly set to the for-
  5356.              mat of your choice by assigning the name to  the  $^
  5357.              variable  while  the  filehandle  is  selected.  The
  5358.              number of lines remaining on the current page is  in
  5359.              variable  $-,  which  can be set to 0 to force a new
  5360.              page.
  5361.  
  5362.              If FILEHANDLE is unspecified,  output  goes  to  the
  5363.              current  default output channel, which starts out as
  5364.              _S_T_D_O_U_T but may be changed by  the  _s_e_l_e_c_t  operator.
  5365.              If the FILEHANDLE is an EXPR, then the expression is
  5366.              evaluated and the resulting string is used  to  look
  5367.              up the name of the FILEHANDLE at run time.  For more
  5368.              on formats, see the section on formats later on.
  5369.  
  5370.              Note that write is NOT the opposite of read.
  5371.  
  5372.      PPPPrrrreeeecccceeeeddddeeeennnncccceeee
  5373.  
  5374.      _P_e_r_l operators have the  following  associativity  and  pre-
  5375.      cedence:
  5376.  
  5377.      nonassoc  print printf exec system sort reverse
  5378.                     chmod chown kill unlink utime die return
  5379.      left      ,
  5380.      right     = += -= *= etc.
  5381.      right     ?:
  5382.      nonassoc  ..
  5383.      left      ||
  5384.      left      &&
  5385.      left      | ^
  5386.      left      &
  5387.      nonassoc  == != <=> eq ne cmp
  5388.      nonassoc  < > <= >= lt gt le ge
  5389.      nonassoc  chdir exit eval reset sleep rand umask
  5390.      nonassoc  -r -w -x etc.
  5391.      left      << >>
  5392.      left      + - .
  5393.      left      * / % x
  5394.      left      =~ !~
  5395.      right     ! ~ and unary minus
  5396.      right     **
  5397.      nonassoc  ++ --
  5398.      left      '('
  5399.  
  5400.      As mentioned earlier, if any list operator (print, etc.)  or
  5401.      any  unary  operator  (chdir,  etc.)   is followed by a left
  5402.      parenthesis as the next token on the same line, the operator
  5403.      and  arguments within parentheses are taken to be of highest
  5404.      precedence, just like a normal function call.  Examples:
  5405.  
  5406.  
  5407.  
  5408.  
  5409. Consensys Computer Inc.                                        82
  5410.  
  5411.  
  5412.  
  5413.  
  5414.  
  5415.  
  5416. PERL(1)                  USER COMMANDS                    PERL(1)
  5417.  
  5418.  
  5419.  
  5420.           chdir $foo || die;       # (chdir $foo) || die
  5421.           chdir($foo) || die;      # (chdir $foo) || die
  5422.           chdir ($foo) || die;     # (chdir $foo) || die
  5423.           chdir +($foo) || die;    # (chdir $foo) || die
  5424.  
  5425.      but, because * is higher precedence than ||:
  5426.  
  5427.           chdir $foo * 20;         # chdir ($foo * 20)
  5428.           chdir($foo) * 20;        # (chdir $foo) * 20
  5429.           chdir ($foo) * 20;       # (chdir $foo) * 20
  5430.           chdir +($foo) * 20;      # chdir ($foo * 20)
  5431.  
  5432.           rand 10 * 20;            # rand (10 * 20)
  5433.           rand(10) * 20;           # (rand 10) * 20
  5434.           rand (10) * 20;          # (rand 10) * 20
  5435.           rand +(10) * 20;         # rand (10 * 20)
  5436.  
  5437.      In the absence of parentheses, the precedence of list opera-
  5438.      tors  such  as  print,  sort or chmod is either very high or
  5439.      very low depending on whether you look at the left  side  of
  5440.      operator or the right side of it.  For example, in
  5441.  
  5442.           @ary = (1, 3, sort 4, 2);
  5443.           print @ary;         # prints 1324
  5444.  
  5445.      the commas on the right of the sort are evaluated before the
  5446.      sort,  but  the  commas on the left are evaluated after.  In
  5447.      other words, list operators tend to gobble up all the  argu-
  5448.      ments that follow them, and then act like a simple term with
  5449.      regard to the preceding expression.  Note that you  have  to
  5450.      be careful with parens:
  5451.  
  5452.           # These evaluate exit before doing the print:
  5453.           print($foo, exit);  # Obviously not what you want.
  5454.           print $foo, exit;   # Nor is this.
  5455.  
  5456.           # These do the print before evaluating exit:
  5457.           (print $foo), exit; # This is what you want.
  5458.           print($foo), exit;  # Or this.
  5459.           print ($foo), exit; # Or even this.
  5460.  
  5461.      Also note that
  5462.  
  5463.           print ($foo & 255) + 1, "\n";
  5464.  
  5465.      probably doesn't do what you expect at first glance.
  5466.  
  5467.      SSSSuuuubbbbrrrroooouuuuttttiiiinnnneeeessss
  5468.  
  5469.      A subroutine may be declared as follows:
  5470.  
  5471.          sub NAME BLOCK
  5472.  
  5473.  
  5474.  
  5475. Consensys Computer Inc.                                        83
  5476.  
  5477.  
  5478.  
  5479.  
  5480.  
  5481.  
  5482. PERL(1)                  USER COMMANDS                    PERL(1)
  5483.  
  5484.  
  5485.  
  5486.      Any arguments passed to the routine come  in  as  array  @_,
  5487.      that is ($_[0], $_[1], ...).  The array @_ is a local array,
  5488.      but its values are references to the actual  scalar  parame-
  5489.      ters.   The  return  value of the subroutine is the value of
  5490.      the last expression evaluated, and can be  either  an  array
  5491.      value  or  a  scalar value.  Alternately, a return statement
  5492.      may be used to specify the returned value and exit the  sub-
  5493.      routine.  To create local variables see the _l_o_c_a_l operator.
  5494.  
  5495.      A subroutine is called using the _d_o operator or the & opera-
  5496.      tor.
  5497.  
  5498.      Example:
  5499.  
  5500.           sub MAX {
  5501.                local($max) = pop(@_);
  5502.                foreach $foo (@_) {
  5503.                     $max = $foo if $max < $foo;
  5504.                }
  5505.                $max;
  5506.           }
  5507.  
  5508.           ...
  5509.           $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
  5510.  
  5511.      Example:
  5512.  
  5513.           # get a line, combining continuation lines
  5514.           #  that start with whitespace
  5515.           sub get_line {
  5516.                $thisline = $lookahead;
  5517.                line: while ($lookahead = <STDIN>) {
  5518.                     if ($lookahead =~ /^[ \t]/) {
  5519.                          $thisline .= $lookahead;
  5520.                     }
  5521.                     else {
  5522.                          last line;
  5523.                     }
  5524.                }
  5525.                $thisline;
  5526.           }
  5527.  
  5528.           $lookahead = <STDIN>;    # get first line
  5529.           while ($_ = do get_line()) {
  5530.                ...
  5531.           }
  5532.  
  5533.  
  5534.  
  5535.  
  5536.  
  5537.  
  5538.  
  5539.  
  5540.  
  5541. Consensys Computer Inc.                                        84
  5542.  
  5543.  
  5544.  
  5545.  
  5546.  
  5547.  
  5548. PERL(1)                  USER COMMANDS                    PERL(1)
  5549.  
  5550.  
  5551.  
  5552.      Use array assignment to a local list to name your formal arguments:
  5553.  
  5554.           sub maybeset {
  5555.                local($key, $value) = @_;
  5556.                $foo{$key} = $value unless $foo{$key};
  5557.           }
  5558.  
  5559.      This also has the effect of turning  call-by-reference  into
  5560.      call-by-value, since the assignment copies the values.
  5561.  
  5562.      Subroutines may be called recursively.  If a  subroutine  is
  5563.      called  using the & form, the argument list is optional.  If
  5564.      omitted, no @_ array is set up for the  subroutine;  the  @_
  5565.      array  at  the  time  of  the  call is visible to subroutine
  5566.      instead.
  5567.  
  5568.           do foo(1,2,3);      # pass three arguments
  5569.           &foo(1,2,3);        # the same
  5570.  
  5571.           do foo();      # pass a null list
  5572.           &foo();             # the same
  5573.           &foo;               # pass no arguments--more efficient
  5574.  
  5575.  
  5576.      PPPPaaaassssssssiiiinnnngggg BBBByyyy RRRReeeeffffeeeerrrreeeennnncccceeee
  5577.  
  5578.      Sometimes you don't want to pass the value of an array to  a
  5579.      subroutine but rather the name of it, so that the subroutine
  5580.      can modify the global copy of it rather than working with  a
  5581.      local  copy.   In perl you can refer to all the objects of a
  5582.      particular name by prefixing the name  with  a  star:  *foo.
  5583.      When  evaluated,  it produces a scalar value that represents
  5584.      all the objects of that name, including any filehandle, for-
  5585.      mat or subroutine.  When assigned to within a local() opera-
  5586.      tion, it causes the name mentioned to refer  to  whatever  *
  5587.      value was assigned to it.  Example:
  5588.  
  5589.           sub doubleary {
  5590.               local(*someary) = @_;
  5591.               foreach $elem (@someary) {
  5592.                $elem *= 2;
  5593.               }
  5594.           }
  5595.           do doubleary(*foo);
  5596.           do doubleary(*bar);
  5597.  
  5598.      Assignment to *name is currently recommended only  inside  a
  5599.      local().  You can actually assign to *name anywhere, but the
  5600.      previous referent of *name may be  stranded  forever.   This
  5601.      may or may not bother you.
  5602.  
  5603.      Note that scalars are already passed by  reference,  so  you
  5604.  
  5605.  
  5606.  
  5607. Consensys Computer Inc.                                        85
  5608.  
  5609.  
  5610.  
  5611.  
  5612.  
  5613.  
  5614. PERL(1)                  USER COMMANDS                    PERL(1)
  5615.  
  5616.  
  5617.  
  5618.      can  modify scalar arguments without using this mechanism by
  5619.      referring explicitly to the $_[nnn] in  question.   You  can
  5620.      modify  all the elements of an array by passing all the ele-
  5621.      ments as scalars, but you have to use  the  *  mechanism  to
  5622.      push,  pop  or change the size of an array.  The * mechanism
  5623.      will probably be more efficient in any case.
  5624.  
  5625.      Since a *name value contains unprintable binary data, if  it
  5626.      is  used as an argument in a print, or as a %s argument in a
  5627.      printf or sprintf, it then has the value '*name', just so it
  5628.      prints out pretty.
  5629.  
  5630.      Even if you don't want to modify an array, this mechanism is
  5631.      useful  for  passing multiple arrays in a single LIST, since
  5632.      normally the LIST mechanism will merge all the array  values
  5633.      so that you can't extract out the individual arrays.
  5634.  
  5635.      RRRReeeegggguuuullllaaaarrrr EEEExxxxpppprrrreeeessssssssiiiioooonnnnssss
  5636.  
  5637.      The patterns used in pattern matching  are  regular  expres-
  5638.      sions  such  as  those supplied in the Version 8 regexp rou-
  5639.      tines.  (In  fact,  the  routines  are  derived  from  Henry
  5640.      Spencer's  freely redistributable reimplementation of the V8
  5641.      routines.)  In addition, \w matches an alphanumeric  charac-
  5642.      ter  (including  "_")  and \W a nonalphanumeric.  Word boun-
  5643.      daries may be matched by \b, and non-boundaries  by  \B.   A
  5644.      whitespace character is matched by \s, non-whitespace by \S.
  5645.      A numeric character is matched by  \d,  non-numeric  by  \D.
  5646.      You  may  use \w, \s and \d within character classes.  Also,
  5647.      \n, \r, \f, \t and \NNN have their  normal  interpretations.
  5648.      Within character classes \b represents backspace rather than
  5649.      a word boundary.  Alternatives may be separated by  |.   The
  5650.      bracketing construct ( ... ) may also be used, in which case
  5651.      \<digit> matches the digit'th substring.   (Outside  of  the
  5652.      pattern,  always  use  $ instead of \ in front of the digit.
  5653.      The scope of $<digit> (and $`, $& and $') extends to the end
  5654.      of  the  enclosing BLOCK or eval string, or to the next pat-
  5655.      tern match with subexpressions.  The \<digit> notation some-
  5656.      times  works  outside the current pattern, but should not be
  5657.      relied upon.)  You may have as many parentheses as you wish.
  5658.      If  you have more than 9 substrings, the variables $10, $11,
  5659.      ... refer to the corresponding substring.  Within  the  pat-
  5660.      tern,  \10, \11, etc. refer back to substrings if there have
  5661.      been at least that many left parens  before  the  backrefer-
  5662.      ence.  Otherwise (for backward compatibilty) \10 is the same
  5663.      as \010, a backspace, and \11 the same as \011, a tab.   And
  5664.      so on.  (\1 through \9 are always backreferences.)
  5665.  
  5666.      $+ returns whatever the  last  bracket  match  matched.   $&
  5667.      returns  the  entire matched string.  ($0 used to return the
  5668.      same thing, but not any more.)  $` returns everything before
  5669.      the matched string.  $' returns everything after the matched
  5670.  
  5671.  
  5672.  
  5673. Consensys Computer Inc.                                        86
  5674.  
  5675.  
  5676.  
  5677.  
  5678.  
  5679.  
  5680. PERL(1)                  USER COMMANDS                    PERL(1)
  5681.  
  5682.  
  5683.  
  5684.      string.  Examples:
  5685.  
  5686.           s/^([^ ]*) *([^ ]*)/$2 $1/;   # swap first two words
  5687.  
  5688.           if (/Time: (..):(..):(..)/) {
  5689.                $hours = $1;
  5690.                $minutes = $2;
  5691.                $seconds = $3;
  5692.           }
  5693.  
  5694.      By default, the ^ character is only guaranteed to  match  at
  5695.      the beginning of the string, the $ character only at the end
  5696.      (or before the newline at the end)  and  _p_e_r_l  does  certain
  5697.      optimizations  with  the assumption that the string contains
  5698.      only one line.  The behavior of ^ and $ on embedded newlines
  5699.      will  be  inconsistent.   You  may, however, wish to treat a
  5700.      string as a multi-line buffer, such that the  ^  will  match
  5701.      after any newline within the string, and $ will match before
  5702.      any newline.  At the cost of a little more overhead, you can
  5703.      do this by setting the variable $* to 1.  Setting it back to
  5704.      0 makes _p_e_r_l revert to its old behavior.
  5705.  
  5706.      To facilitate  multi-line  substitutions,  the  .  character
  5707.      never matches a newline (even when $* is 0).  In particular,
  5708.      the following leaves a newline on the $_ string:
  5709.  
  5710.           $_ = <STDIN>;
  5711.           s/.*(some_string).*/$1/;
  5712.  
  5713.      If the newline is unwanted, try one of
  5714.  
  5715.           s/.*(some_string).*\n/$1/;
  5716.           s/.*(some_string)[^\000]*/$1/;
  5717.           s/.*(some_string)(.|\n)*/$1/;
  5718.           chop; s/.*(some_string).*/$1/;
  5719.           /(some_string)/ && ($_ = $1);
  5720.  
  5721.      Any item of a regular expression may be followed with digits
  5722.      in  curly  brackets  of  the  form  {n,m}, where n gives the
  5723.      minimum number of times to match the item and  m  gives  the
  5724.      maximum.   The  form  {n} is equivalent to {n,n} and matches
  5725.      exactly n times.  The form {n,} matches  n  or  more  times.
  5726.      (If  a  curly  bracket  occurs  in  any other context, it is
  5727.      treated  as  a  regular  character.)   The  *  modifier   is
  5728.      equivalent  to {0,}, the + modifier to {1,} and the ? modif-
  5729.      ier to {0,1}.  There is no limit to the size of n or m,  but
  5730.      large numbers will chew up more memory.
  5731.  
  5732.      You will note that all backslashed  metacharacters  in  _p_e_r_l
  5733.      are  alphanumeric,  such  as  \b, \w, \n.  Unlike some other
  5734.      regular expression languages, there are no backslashed  sym-
  5735.      bols  that aren't alphanumeric.  So anything that looks like
  5736.  
  5737.  
  5738.  
  5739. Consensys Computer Inc.                                        87
  5740.  
  5741.  
  5742.  
  5743.  
  5744.  
  5745.  
  5746. PERL(1)                  USER COMMANDS                    PERL(1)
  5747.  
  5748.  
  5749.  
  5750.      \\, \(, \), \<, \>, \{, or \} is  always  interpreted  as  a
  5751.      literal  character, not a metacharacter.  This makes it sim-
  5752.      ple to quote a string that you want to use for a pattern but
  5753.      that  you  are  afraid might contain metacharacters.  Simply
  5754.      quote all the non-alphanumeric characters:
  5755.  
  5756.           $pattern =~ s/(\W)/\\$1/g;
  5757.  
  5758.  
  5759.      FFFFoooorrrrmmmmaaaattttssss
  5760.  
  5761.      Output record formats for use with the  _w_r_i_t_e  operator  may
  5762.      declared as follows:
  5763.  
  5764.          format NAME =
  5765.          FORMLIST
  5766.          .
  5767.  
  5768.      If name is omitted, format "STDOUT"  is  defined.   FORMLIST
  5769.      consists of a sequence of lines, each of which may be of one
  5770.      of three types:
  5771.  
  5772.      1.  A comment.
  5773.  
  5774.      2.  A "picture" line giving the format for one output line.
  5775.  
  5776.      3.  An argument line supplying values to plug into a picture
  5777.          line.
  5778.  
  5779.      Picture lines are printed exactly as they look,  except  for
  5780.      certain  fields  that substitute values into the line.  Each
  5781.      picture field starts with either @ or ^.  The @  field  (not
  5782.      to  be confused with the array marker @) is the normal case;
  5783.      ^ fields are used to do rudimentary  multi-line  text  block
  5784.      filling.  The length of the field is supplied by padding out
  5785.      the field with multiple <, >, or |  characters  to  specify,
  5786.      respectively,  left  justification,  right justification, or
  5787.      centering.  As an alternate form of right justification, you
  5788.      may  also use # characters (with an optional .) to specify a
  5789.      numeric field.  (Use of ^ instead of @ causes the  field  to
  5790.      be blanked if undefined.)  If any of the values supplied for
  5791.      these fields contains a newline, only the  text  up  to  the
  5792.      newline  is  printed.   The special field @* can be used for
  5793.      printing multi-line values.  It should appear by itself on a
  5794.      line.
  5795.  
  5796.      The values are specified on the following line, in the  same
  5797.      order as the picture fields.  The values should be separated
  5798.      by commas.
  5799.  
  5800.      Picture fields that begin with ^ rather than @  are  treated
  5801.      specially.   The  value  supplied  must be a scalar variable
  5802.  
  5803.  
  5804.  
  5805. Consensys Computer Inc.                                        88
  5806.  
  5807.  
  5808.  
  5809.  
  5810.  
  5811.  
  5812. PERL(1)                  USER COMMANDS                    PERL(1)
  5813.  
  5814.  
  5815.  
  5816.      name which contains a text string.  _P_e_r_l puts as  much  text
  5817.      as  it  can  into the field, and then chops off the front of
  5818.      the string so that the next time the variable is referenced,
  5819.      more  of  the text can be printed.  Normally you would use a
  5820.      sequence of fields in a vertical stack to print out a  block
  5821.      of text.  If you like, you can end the final field with ...,
  5822.      which will appear in the output if the text was too long  to
  5823.      appear in its entirety.  You can change which characters are
  5824.      legal to break on by changing the variable $: to a  list  of
  5825.      the desired characters.
  5826.  
  5827.      Since use of ^ fields can produce variable length records if
  5828.      the  text  to  be formatted is short, you can suppress blank
  5829.      lines by putting the tilde (~)  character  anywhere  in  the
  5830.      line.  (Normally you should put it in the front if possible,
  5831.      for visibility.)  The tilde will be translated  to  a  space
  5832.      upon  output.   If  you put a second tilde contiguous to the
  5833.      first, the line will be repeated until all the fields on the
  5834.      line  are  exhausted.  (If you use a field of the @ variety,
  5835.      the expression you supply had better not give the same value
  5836.      every time forever!)
  5837.  
  5838.      Examples:
  5839.  
  5840.      # a report on the /etc/passwd file
  5841.      format STDOUT_TOP =
  5842.                              Passwd File
  5843.      Name                Login    Office   Uid   Gid Home
  5844.      ------------------------------------------------------------------
  5845.      .
  5846.      format STDOUT =
  5847.      @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
  5848.      $name,              $login,  $office,$uid,$gid, $home
  5849.      .
  5850.  
  5851.  
  5852.  
  5853.  
  5854.  
  5855.  
  5856.  
  5857.  
  5858.  
  5859.  
  5860.  
  5861.  
  5862.  
  5863.  
  5864.  
  5865.  
  5866.  
  5867.  
  5868.  
  5869.  
  5870.  
  5871. Consensys Computer Inc.                                        89
  5872.  
  5873.  
  5874.  
  5875.  
  5876.  
  5877.  
  5878. PERL(1)                  USER COMMANDS                    PERL(1)
  5879.  
  5880.  
  5881.  
  5882.      # a report from a bug report form
  5883.      format STDOUT_TOP =
  5884.                              Bug Reports
  5885.      @<<<<<<<<<<<<<<<<<<<<<<<     @|||         @>>>>>>>>>>>>>>>>>>>>>>>
  5886.      $system,                      $%,         $date
  5887.      ------------------------------------------------------------------
  5888.      .
  5889.      format STDOUT =
  5890.      Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5891.               $subject
  5892.      Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5893.             $index,                       $description
  5894.      Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5895.                $priority,        $date,   $description
  5896.      From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5897.            $from,                         $description
  5898.      Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5899.                   $programmer,            $description
  5900.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5901.                                           $description
  5902.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5903.                                           $description
  5904.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5905.                                           $description
  5906.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5907.                                           $description
  5908.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<...
  5909.                                           $description
  5910.      .
  5911.  
  5912.      It is possible to intermix prints with writes  on  the  same
  5913.      output  channel, but you'll have to handle $- (lines left on
  5914.      the page) yourself.
  5915.  
  5916.      If you are printing lots of fields that are  usually  blank,
  5917.      you   should  consider  using  the  reset  operator  between
  5918.      records.  Not only is it more efficient, but it can  prevent
  5919.      the bug of adding another field and forgetting to zero it.
  5920.  
  5921.      IIIInnnntttteeeerrrrpppprrrroooocccceeeessssssss CCCCoooommmmmmmmuuuunnnniiiiccccaaaattttiiiioooonnnn
  5922.  
  5923.      The IPC facilities of perl are built on the Berkeley  socket
  5924.      mechanism.   If  you don't have sockets, you can ignore this
  5925.      section.  (Sockets are not yet supported  on  MS-DOS.)   The
  5926.      calls have the same names as the corresponding system calls,
  5927.      but the arguments tend to differ, for two  reasons.   First,
  5928.      perl  file handles work differently than C file descriptors.
  5929.      Second, perl already knows the length of its strings, so you
  5930.      don't  need  to  pass  that  information.   Here is a sample
  5931.      client (untested):
  5932.  
  5933.           ($them,$port) = @ARGV;
  5934.  
  5935.  
  5936.  
  5937. Consensys Computer Inc.                                        90
  5938.  
  5939.  
  5940.  
  5941.  
  5942.  
  5943.  
  5944. PERL(1)                  USER COMMANDS                    PERL(1)
  5945.  
  5946.  
  5947.  
  5948.           $port = 2345 unless $port;
  5949.           $them = 'localhost' unless $them;
  5950.  
  5951.           $SIG{'INT'} = 'dokill';
  5952.           sub dokill { kill 9,$child if $child; }
  5953.  
  5954.           require 'sys/socket.ph';
  5955.  
  5956.           $sockaddr = 'S n a4 x8';
  5957.           chop($hostname = `hostname`);
  5958.  
  5959.           ($name, $aliases, $proto) = getprotobyname('tcp');
  5960.           ($name, $aliases, $port) = getservbyname($port, 'tcp')
  5961.                unless $port =~ /^\d+$/;
  5962.           ($name, $aliases, $type, $len, $thisaddr) =
  5963.                               gethostbyname($hostname);
  5964.           ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
  5965.  
  5966.           $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
  5967.           $that = pack($sockaddr, &AF_INET, $port, $thataddr);
  5968.  
  5969.           socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  5970.           bind(S, $this) || die "bind: $!";
  5971.           connect(S, $that) || die "connect: $!";
  5972.  
  5973.           select(S); $| = 1; select(stdout);
  5974.  
  5975.           if ($child = fork) {
  5976.                while (<>) {
  5977.                     print S;
  5978.                }
  5979.                sleep 3;
  5980.                do dokill();
  5981.           }
  5982.           else {
  5983.                while (<S>) {
  5984.                     print;
  5985.                }
  5986.           }
  5987.  
  5988.      And here's a server:
  5989.  
  5990.           ($port) = @ARGV;
  5991.           $port = 2345 unless $port;
  5992.  
  5993.           require 'sys/socket.ph';
  5994.  
  5995.           $sockaddr = 'S n a4 x8';
  5996.  
  5997.           ($name, $aliases, $proto) = getprotobyname('tcp');
  5998.           ($name, $aliases, $port) = getservbyname($port, 'tcp')
  5999.                unless $port =~ /^\d+$/;
  6000.  
  6001.  
  6002.  
  6003. Consensys Computer Inc.                                        91
  6004.  
  6005.  
  6006.  
  6007.  
  6008.  
  6009.  
  6010. PERL(1)                  USER COMMANDS                    PERL(1)
  6011.  
  6012.  
  6013.  
  6014.           $this = pack($sockaddr, &AF_INET, $port, "\0\0\0\0");
  6015.  
  6016.           select(NS); $| = 1; select(stdout);
  6017.  
  6018.           socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  6019.           bind(S, $this) || die "bind: $!";
  6020.           listen(S, 5) || die "connect: $!";
  6021.  
  6022.           select(S); $| = 1; select(stdout);
  6023.  
  6024.           for (;;) {
  6025.                print "Listening again\n";
  6026.                ($addr = accept(NS,S)) || die $!;
  6027.                print "accept ok\n";
  6028.  
  6029.                ($af,$port,$inetaddr) = unpack($sockaddr,$addr);
  6030.                @inetaddr = unpack('C4',$inetaddr);
  6031.                print "$af $port @inetaddr\n";
  6032.  
  6033.                while (<NS>) {
  6034.                     print;
  6035.                     print NS;
  6036.                }
  6037.           }
  6038.  
  6039.  
  6040.  
  6041.      PPPPrrrreeeeddddeeeeffffiiiinnnneeeedddd NNNNaaaammmmeeeessss
  6042.  
  6043.      The following names have special meaning to _p_e_r_l.   I  could
  6044.      have used alphabetic symbols for some of these, but I didn't
  6045.      want to  take  the  chance  that  someone  would  say  reset
  6046.      "a-zA-Z"  and wipe them all out.  You'll just have to suffer
  6047.      along with these silly symbols.  Most of them  have  reason-
  6048.      able mnemonics, or analogues in one of the shells.
  6049.  
  6050.      $_      The default input and pattern-searching space.   The
  6051.              following pairs are equivalent:
  6052.  
  6053.                   while (<>) {...     # only equivalent in while!
  6054.                   while ($_ = <>) {...
  6055.  
  6056.                   /^Subject:/
  6057.                   $_ =~ /^Subject:/
  6058.  
  6059.                   y/a-z/A-Z/
  6060.                   $_ =~ y/a-z/A-Z/
  6061.  
  6062.                   chop
  6063.                   chop($_)
  6064.  
  6065.              (Mnemonic:  underline  is  understood   in   certain
  6066.  
  6067.  
  6068.  
  6069. Consensys Computer Inc.                                        92
  6070.  
  6071.  
  6072.  
  6073.  
  6074.  
  6075.  
  6076. PERL(1)                  USER COMMANDS                    PERL(1)
  6077.  
  6078.  
  6079.  
  6080.              operations.)
  6081.  
  6082.      $.      The current input line number of the last filehandle
  6083.              that  was  read.   Readonly.   Remember that only an
  6084.              explicit close on the  filehandle  resets  the  line
  6085.              number.  Since <> never does an explicit close, line
  6086.              numbers increase across ARGV files (but see examples
  6087.              under  eof).  (Mnemonic: many programs use . to mean
  6088.              the current line number.)
  6089.  
  6090.      $/      The input  record  separator,  newline  by  default.
  6091.              Works  like  _a_w_k's  RS  variable, including treating
  6092.              blank lines as delimiters if set to the null string.
  6093.              You may set it to a multicharacter string to match a
  6094.              multi-character delimiter.  (Mnemonic: / is used  to
  6095.              delimit line boundaries when quoting poetry.)
  6096.  
  6097.      $,      The output field separator for the  print  operator.
  6098.              Ordinarily  the print operator simply prints out the
  6099.              comma separated fields you specify.  In order to get
  6100.              behavior  more  like  _a_w_k,  set this variable as you
  6101.              would set _a_w_k's OFS  variable  to  specify  what  is
  6102.              printed  between fields.  (Mnemonic: what is printed
  6103.              when there is a , in your print statement.)
  6104.  
  6105.      $"      This is like $, except  that  it  applies  to  array
  6106.              values  interpolated into a double-quoted string (or
  6107.              similar interpreted string).  Default  is  a  space.
  6108.              (Mnemonic: obvious, I think.)
  6109.  
  6110.      $\      The output record separator for the print  operator.
  6111.              Ordinarily  the print operator simply prints out the
  6112.              comma separated fields you specify, with no trailing
  6113.              newline  or  record  separator assumed.  In order to
  6114.              get behavior more like _a_w_k, set this variable as you
  6115.              would  set  _a_w_k's  ORS  variable  to specify what is
  6116.              printed at the end of the print.  (Mnemonic: you set
  6117.              $\  instead  of  adding  \n at the end of the print.
  6118.              Also, it's just like /, but it's what you get "back"
  6119.              from _p_e_r_l.)
  6120.  
  6121.      $#      The output format for printed numbers.   This  vari-
  6122.              able is a half-hearted attempt to emulate _a_w_k's OFMT
  6123.              variable.  There are times, however,  when  _a_w_k  and
  6124.              _p_e_r_l  have  differing  notions  of  what  is in fact
  6125.              numeric.  Also, the initial value  is  %.20g  rather
  6126.              than  %.6g,  so you need to set $# explicitly to get
  6127.              _a_w_k's value.  (Mnemonic: # is the number sign.)
  6128.  
  6129.      $%      The current page number of  the  currently  selected
  6130.              output  channel.   (Mnemonic:  %  is  page number in
  6131.              nroff.)
  6132.  
  6133.  
  6134.  
  6135. Consensys Computer Inc.                                        93
  6136.  
  6137.  
  6138.  
  6139.  
  6140.  
  6141.  
  6142. PERL(1)                  USER COMMANDS                    PERL(1)
  6143.  
  6144.  
  6145.  
  6146.      $=      The current page length  (printable  lines)  of  the
  6147.              currently  selected  output channel.  Default is 60.
  6148.              (Mnemonic: = has horizontal lines.)
  6149.  
  6150.      $-      The  number  of  lines  left  on  the  page  of  the
  6151.              currently   selected   output  channel.   (Mnemonic:
  6152.              lines_on_page - lines_printed.)
  6153.  
  6154.      $~      The name  of  the  current  report  format  for  the
  6155.              currently  selected output channel.  Default is name
  6156.              of the filehandle.  (Mnemonic: brother to $^.)
  6157.  
  6158.      $^      The name of the current top-of-page format  for  the
  6159.              currently  selected output channel.  Default is name
  6160.              of the filehandle with "_TOP" appended.   (Mnemonic:
  6161.              points to top of page.)
  6162.  
  6163.      $|      If set to nonzero, forces a flush after every  write
  6164.              or  print  on the currently selected output channel.
  6165.              Default is 0.  Note that _S_T_D_O_U_T  will  typically  be
  6166.              line buffered if output is to the terminal and block
  6167.              buffered otherwise.  Setting this variable is useful
  6168.              primarily when you are outputting to a pipe, such as
  6169.              when you are running a _p_e_r_l  script  under  rsh  and
  6170.              want   to   see   the   output  as  it's  happening.
  6171.              (Mnemonic: when you want your  pipes  to  be  piping
  6172.              hot.)
  6173.  
  6174.      $$      The process number of the _p_e_r_l running this  script.
  6175.              (Mnemonic:  same  as  shells.)   On  MS-DOS, this is
  6176.              _p_e_r_l's PSP (program segment prefix) segment.
  6177.  
  6178.      $?      The status returned by the last pipe close, backtick
  6179.              (``)  command or _s_y_s_t_e_m operator.  Note that this is
  6180.              the status word returned by the wait() system  call,
  6181.              so  the exit value of the subprocess is actually ($?
  6182.              >> 8).  $? & 255 gives which  signal,  if  any,  the
  6183.              process  died  from,  and  whether  there was a core
  6184.              dump.  MS-DOS users  should  note  that  the  MS-DOS
  6185.              return values are fudged internally so that $? gives
  6186.              Unix-like results.  (Mnemonic:  similar  to  sh  and
  6187.              ksh.)
  6188.  
  6189.      $&      The string matched by the last  pattern  match  (not
  6190.              counting  any  matches hidden within a BLOCK or eval
  6191.              enclosed by the current BLOCK).  (Mnemonic:  like  &
  6192.              in some editors.)
  6193.  
  6194.      $`      The string preceding whatever  was  matched  by  the
  6195.              last  pattern match (not counting any matches hidden
  6196.              within a BLOCK  or  eval  enclosed  by  the  current
  6197.              BLOCK).    (Mnemonic:  `  often  precedes  a  quoted
  6198.  
  6199.  
  6200.  
  6201. Consensys Computer Inc.                                        94
  6202.  
  6203.  
  6204.  
  6205.  
  6206.  
  6207.  
  6208. PERL(1)                  USER COMMANDS                    PERL(1)
  6209.  
  6210.  
  6211.  
  6212.              string.)
  6213.  
  6214.      $'      The string following whatever  was  matched  by  the
  6215.              last  pattern match (not counting any matches hidden
  6216.              within a BLOCK  or  eval  enclosed  by  the  current
  6217.              BLOCK).    (Mnemonic:   '  often  follows  a  quoted
  6218.              string.)  Example:
  6219.  
  6220.                   $_ = 'abcdefghi';
  6221.                   /def/;
  6222.                   print "$`:$&:$'\n";      # prints abc:def:ghi
  6223.  
  6224.  
  6225.      $+      The last bracket matched by the last search pattern.
  6226.              This  is  useful if you don't know which of a set of
  6227.              alternative patterns matched.  For example:
  6228.  
  6229.                  /Version: (.*)|Revision: (.*)/ && ($rev = $+);
  6230.  
  6231.              (Mnemonic: be positive and forward looking.)
  6232.  
  6233.      $*      Set to 1 to do multiline matching within a string, 0
  6234.              to tell _p_e_r_l that it can assume that strings contain
  6235.              a single line, for the purpose of optimizing pattern
  6236.              matches.  Pattern matches on strings containing mul-
  6237.              tiple newlines can produce confusing results when $*
  6238.              is  0.  Default is 0.  (Mnemonic: * matches multiple
  6239.              things.)  Note that this  variable  only  influences
  6240.              the  interpretation  of  ^ and $.  A literal newline
  6241.              can be searched for even when $* == 0.
  6242.  
  6243.      $0      Contains the name of the file  containing  the  _p_e_r_l
  6244.              script being executed.  Assigning to $0 modifies the
  6245.              argument  area  that   the   ps(1)   program   sees.
  6246.              (Mnemonic: same as sh and ksh.)
  6247.  
  6248.      $<digit>
  6249.              Contains the subpattern from the  corresponding  set
  6250.              of  parentheses  in  the  last  pattern matched, not
  6251.              counting patterns matched in nested blocks that have
  6252.              been exited already.  (Mnemonic: like \digit.)
  6253.  
  6254.      $[      The index of the first element in an array,  and  of
  6255.              the  first  character in a substring.  Default is 0,
  6256.              but you could set it to 1 to make _p_e_r_l  behave  more
  6257.              like  _a_w_k  (or  Fortran)  when subscripting and when
  6258.              evaluating  the  index()  and  substr()   functions.
  6259.              (Mnemonic: [ begins subscripts.)
  6260.  
  6261.      $]      The string printed out when you say "perl  -v".   It
  6262.              can  be  used  to  determine  at  the beginning of a
  6263.              script whether the perl  interpreter  executing  the
  6264.  
  6265.  
  6266.  
  6267. Consensys Computer Inc.                                        95
  6268.  
  6269.  
  6270.  
  6271.  
  6272.  
  6273.  
  6274. PERL(1)                  USER COMMANDS                    PERL(1)
  6275.  
  6276.  
  6277.  
  6278.              script  is  in the right range of versions.  If used
  6279.              in  a  numeric  context,  returns  the   version   +
  6280.              patchlevel / 1000.  Example:
  6281.  
  6282.                   # see if getc is available
  6283.                      ($version,$patchlevel) =
  6284.                         $] =~ /(\d+\.\d+).*\nPatch level: (\d+)/;
  6285.                      print STDERR "(No filename completion available.)\n"
  6286.                         if $version * 1000 + $patchlevel < 2016;
  6287.  
  6288.              or, used numerically,
  6289.  
  6290.                   warn "No checksumming!\n" if $] < 3.019;
  6291.  
  6292.              (Mnemonic: Is this version  of  perl  in  the  right
  6293.              bracket?)
  6294.  
  6295.      $;      The subscript separator for multi-dimensional  array
  6296.              emulation.   If  you  refer  to an associative array
  6297.              element as
  6298.                   $foo{$a,$b,$c}
  6299.  
  6300.              it really means
  6301.  
  6302.                   $foo{join($;, $a, $b, $c)}
  6303.  
  6304.              But don't put
  6305.  
  6306.                   @foo{$a,$b,$c}      # a slice--note the @
  6307.  
  6308.              which means
  6309.  
  6310.                   ($foo{$a},$foo{$b},$foo{$c})
  6311.  
  6312.              Default is "\034", the same as SUBSEP in _a_w_k.   Note
  6313.              that  if  your  keys contain binary data there might
  6314.              not be any safe value for $;.  (Mnemonic: comma (the
  6315.              syntactic  subscript separator) is a semi-semicolon.
  6316.              Yeah, I know, it's pretty lame, but  $,  is  already
  6317.              taken for something more important.)
  6318.  
  6319.      $!      If used in a numeric  context,  yields  the  current
  6320.              value  of  errno, with all the usual caveats.  (This
  6321.              means that you shouldn't depend on the value  of  $!
  6322.              to  be anything in particular unless you've gotten a
  6323.              specific error return indicating  a  system  error.)
  6324.              If  used in a string context, yields the correspond-
  6325.              ing system error string.  You can assign  to  $!  in
  6326.              order  to set errno if, for instance, you want $! to
  6327.              return the string for error n, or you  want  to  set
  6328.              the  exit  value  for  the die operator.  (Mnemonic:
  6329.              What just went bang?)
  6330.  
  6331.  
  6332.  
  6333. Consensys Computer Inc.                                        96
  6334.  
  6335.  
  6336.  
  6337.  
  6338.  
  6339.  
  6340. PERL(1)                  USER COMMANDS                    PERL(1)
  6341.  
  6342.  
  6343.  
  6344.      $@      The perl syntax error message  from  the  last  eval
  6345.              command.  If null, the last eval parsed and executed
  6346.              correctly (although the operations you  invoked  may
  6347.              have  failed  in  the  normal  fashion).  (Mnemonic:
  6348.              Where was the syntax error "at"?)
  6349.  
  6350.      $<      The real uid of this process.  (Mnemonic:  it's  the
  6351.              uid you came FROM, if you're running setuid.)
  6352.  
  6353.      $>      The effective uid of this process.  Example:
  6354.  
  6355.                   $< = $>;  # set real uid to the effective uid
  6356.                   ($<,$>) = ($>,$<);  # swap real and effective uid
  6357.  
  6358.              (Mnemonic: it's the uid you went TO, if you're  run-
  6359.              ning  setuid.)   Note: $< and $> can only be swapped
  6360.              on machines supporting setreuid().
  6361.  
  6362.      $(      The real gid of this  process.   If  you  are  on  a
  6363.              machine  that supports membership in multiple groups
  6364.              simultaneously, gives  a  space  separated  list  of
  6365.              groups  you  are  in.   The  first number is the one
  6366.              returned by getgid(), and  the  subsequent  ones  by
  6367.              getgroups(),  one  of  which  may be the same as the
  6368.              first number.  (Mnemonic: parentheses  are  used  to
  6369.              GROUP  things.   The real gid is the group you LEFT,
  6370.              if you're running setgid.)
  6371.  
  6372.      $)      The effective gid of this process.  If you are on  a
  6373.              machine  that supports membership in multiple groups
  6374.              simultaneously, gives  a  space  separated  list  of
  6375.              groups  you  are  in.   The  first number is the one
  6376.              returned by getegid(), and the  subsequent  ones  by
  6377.              getgroups(),  one  of  which  may be the same as the
  6378.              first number.  (Mnemonic: parentheses  are  used  to
  6379.              GROUP things.  The effective gid is the group that's
  6380.              RIGHT for you, if you're running setgid.)
  6381.  
  6382.              Note: $<, $>, $( and $) can only be set on  machines
  6383.              that  support the corresponding set[re][ug]id() rou-
  6384.              tine.  $( and $) can only  be  swapped  on  machines
  6385.              supporting setregid().
  6386.  
  6387.      $:      The current set of characters after which  a  string
  6388.              may  be broken to fill continuation fields (starting
  6389.              with ^) in a format.  Default is " \n-", to break on
  6390.              whitespace or hyphens.  (Mnemonic: a "colon" in poe-
  6391.              try is a part of a line.)
  6392.  
  6393.      $^D     The  current   value   of   the   debugging   flags.
  6394.              (Mnemonic: value of ----DDDD switch.)
  6395.  
  6396.  
  6397.  
  6398.  
  6399. Consensys Computer Inc.                                        97
  6400.  
  6401.  
  6402.  
  6403.  
  6404.  
  6405.  
  6406. PERL(1)                  USER COMMANDS                    PERL(1)
  6407.  
  6408.  
  6409.  
  6410.      $^F     The maximum system file  descriptor,  ordinarily  2.
  6411.              System  file descriptors are passed to subprocesses,
  6412.              while higher file descriptors are  not.   During  an
  6413.              open,  system file descriptors are preserved even if
  6414.              the  open  fails.   Ordinary  file  descriptors  are
  6415.              closed before the open is attempted.
  6416.  
  6417.      $^I     The current value  of  the  inplace-edit  extension.
  6418.              Use  undef  to  disable inplace editing.  (Mnemonic:
  6419.              value of ----iiii switch.)
  6420.  
  6421.      $^P     The internal flag that the debugger clears  so  that
  6422.              it doesn't debug itself.  You could conceivable dis-
  6423.              able debugging yourself by clearing it.
  6424.  
  6425.      $^T     The time at  which  the  script  began  running,  in
  6426.              seconds since the epoch.  The values returned by the
  6427.              ----MMMM ,,,, ----AAAA and ----CCCC filetests are based on this value.
  6428.  
  6429.      $^W     The current value of the warning switch.  (Mnemonic:
  6430.              related to the ----wwww switch.)
  6431.  
  6432.      $^X     The name that Perl  itself  was  executed  as,  from
  6433.              argv[0].
  6434.  
  6435.      $ARGV   contains the name of the current file  when  reading
  6436.              from <>.
  6437.  
  6438.      @ARGV   The array ARGV contains the command  line  arguments
  6439.              intended  for  the  script.  Note that $#ARGV is the
  6440.              generally  number  of  arguments  minus  one,  since
  6441.              $ARGV[0]  is  the  first  argument,  NOT the command
  6442.              name.  See $0 for the command name.
  6443.  
  6444.      @INC    The array INC contains the list of  places  to  look
  6445.              for  _p_e_r_l  scripts  to be evaluated by the "do EXPR"
  6446.              command or the "require" command.  It initially con-
  6447.              sists  of  the  arguments  to  any  ----IIII  command line
  6448.              switches, followed by any directories in the PERLLIB
  6449.              environment  variable  (omitted for _t_a_i_n_t_p_e_r_l), fol-
  6450.              lowed  by  the  default   _p_e_r_l   library,   probably
  6451.              "/usr/local/lib/perl", followed by ".", to represent
  6452.              the current directory.
  6453.  
  6454.      %INC    The associative array INC contains entries for  each
  6455.              filename   that   has  been  included  via  "do"  or
  6456.              "require".  The key is the filename  you  specified,
  6457.              and  the  value is the location of the file actually
  6458.              found.  The "require" command  uses  this  array  to
  6459.              determine  whether  a  given  file  has already been
  6460.              included.
  6461.  
  6462.  
  6463.  
  6464.  
  6465. Consensys Computer Inc.                                        98
  6466.  
  6467.  
  6468.  
  6469.  
  6470.  
  6471.  
  6472. PERL(1)                  USER COMMANDS                    PERL(1)
  6473.  
  6474.  
  6475.  
  6476.      $ENV{expr}
  6477.              The associative  array  ENV  contains  your  current
  6478.              environment.   Setting  a  value  in ENV changes the
  6479.              environment for child processes.
  6480.  
  6481.      $SIG{expr}
  6482.              The associative array SIG  is  used  to  set  signal
  6483.              handlers for various signals.  Example:
  6484.  
  6485.                   sub handler {  # 1st argument is signal name
  6486.                        local($sig) = @_;
  6487.                        print "Caught a SIG$sig--shutting down\n";
  6488.                        close(LOG);
  6489.                        exit(0);
  6490.                   }
  6491.  
  6492.                   $SIG{'INT'} = 'handler';
  6493.                   $SIG{'QUIT'} = 'handler';
  6494.                   ...
  6495.                   $SIG{'INT'} = 'DEFAULT'; # restore default action
  6496.                   $SIG{'QUIT'} = 'IGNORE'; # ignore SIGQUIT
  6497.  
  6498.              The SIG array only contains values for  the  signals
  6499.              actually set within the perl script.
  6500.  
  6501.      PPPPaaaacccckkkkaaaaggggeeeessss
  6502.  
  6503.      Perl provides a mechanism for alternate namespaces  to  pro-
  6504.      tect  packages  from  stomping on each others variables.  By
  6505.      default, a perl script starts  compiling  into  the  package
  6506.      known as "main".  By use of the _p_a_c_k_a_g_e declaration, you can
  6507.      switch namespaces.  The scope of the package declaration  is
  6508.      from  the  declaration  itself  to  the end of the enclosing
  6509.      block (the same scope as the local()  operator).   Typically
  6510.      it  would  be the first declaration in a file to be included
  6511.      by the "require" operator.  You can switch into a package in
  6512.      more than one place; it merely influences which symbol table
  6513.      is used by the compiler for the rest of that block.  You can
  6514.      refer to variables and filehandles in other packages by pre-
  6515.      fixing the identifier with the package  name  and  a  single
  6516.      quote.   If  the package name is null, the "main" package as
  6517.      assumed.
  6518.  
  6519.      Only identifiers starting with letters  are  stored  in  the
  6520.      packages  symbol table.  All other symbols are kept in pack-
  6521.      age "main".  In addition,  the  identifiers  STDIN,  STDOUT,
  6522.      STDERR,  ARGV, ARGVOUT, ENV, INC and SIG are forced to be in
  6523.      package "main", even when used for other purposes than their
  6524.      built-in  one.  Note also that, if you have a package called
  6525.      "m", "s" or "y", the you can't use the qualified form of  an
  6526.      identifier since it will be interpreted instead as a pattern
  6527.      match, a substitution or a translation.
  6528.  
  6529.  
  6530.  
  6531. Consensys Computer Inc.                                        99
  6532.  
  6533.  
  6534.  
  6535.  
  6536.  
  6537.  
  6538. PERL(1)                  USER COMMANDS                    PERL(1)
  6539.  
  6540.  
  6541.  
  6542.      Eval'ed strings are compiled in the  package  in  which  the
  6543.      eval  was  compiled  in.   (Assignments  to $SIG{}, however,
  6544.      assume the signal handler specified is in the main  package.
  6545.      Qualify the signal handler name if you wish to have a signal
  6546.      handler in a package.)  For an example, examine perldb.pl in
  6547.      the  perl  library.  It initially switches to the DB package
  6548.      so that the debugger doesn't interfere with variables in the
  6549.      script you are trying to debug.  At various points, however,
  6550.      it temporarily switches back to the main package to evaluate
  6551.      various expressions in the context of the main package.
  6552.  
  6553.      The symbol table for a package happens to be stored  in  the
  6554.      associative array of that name prepended with an underscore.
  6555.      The value in each entry of the associative array is what you
  6556.      are  referring to when you use the *name notation.  In fact,
  6557.      the following have the same effect (in  package  main,  any-
  6558.      way), though the first is more efficient because it does the
  6559.      symbol table lookups at compile time:
  6560.  
  6561.           local(*foo) = *bar;
  6562.           local($_main{'foo'}) = $_main{'bar'};
  6563.  
  6564.      You can use this to print out all the variables in  a  pack-
  6565.      age,  for  instance.   Here  is  dumpvar.pl  from  the  perl
  6566.      library:
  6567.           package dumpvar;
  6568.  
  6569.           sub main'dumpvar {
  6570.               ($package) = @_;
  6571.               local(*stab) = eval("*_$package");
  6572.               while (($key,$val) = each(%stab)) {
  6573.                   {
  6574.                       local(*entry) = $val;
  6575.                       if (defined $entry) {
  6576.                           print "\$$key = '$entry'\n";
  6577.                       }
  6578.                       if (defined @entry) {
  6579.                           print "\@$key = (\n";
  6580.                           foreach $num ($[ .. $#entry) {
  6581.                               print "  $num\t'",$entry[$num],"'\n";
  6582.                           }
  6583.                           print ")\n";
  6584.                       }
  6585.  
  6586.  
  6587.  
  6588.  
  6589.  
  6590.  
  6591.  
  6592.  
  6593.  
  6594.  
  6595.  
  6596.  
  6597. Consensys Computer Inc.                                       100
  6598.  
  6599.  
  6600.  
  6601.  
  6602.  
  6603.  
  6604. PERL(1)                  USER COMMANDS                    PERL(1)
  6605.  
  6606.  
  6607.  
  6608.                       if ($key ne "_$package" && defined %entry) {
  6609.                           print "\%$key = (\n";
  6610.                           foreach $key (sort keys(%entry)) {
  6611.                               print "  $key\t'",$entry{$key},"'\n";
  6612.                           }
  6613.                           print ")\n";
  6614.                       }
  6615.                   }
  6616.               }
  6617.           }
  6618.  
  6619.      Note that, even though the subroutine is compiled in package
  6620.      dumpvar, the name of the subroutine is qualified so that its
  6621.      name is inserted into package "main".
  6622.  
  6623.      SSSSttttyyyylllleeee
  6624.  
  6625.      Each programmer will, of course, have his or her own prefer-
  6626.      ences  in  regards to formatting, but there are some general
  6627.      guidelines that will make your programs easier to read.
  6628.  
  6629.      1.  Just because you  CAN  do  something  a  particular  way
  6630.          doesn't  mean  that  you SHOULD do it that way.  _P_e_r_l is
  6631.          designed to give you several ways  to  do  anything,  so
  6632.          consider picking the most readable one.  For instance
  6633.  
  6634.               open(FOO,$foo) || die "Can't open $foo: $!";
  6635.  
  6636.          is better than
  6637.  
  6638.               die "Can't open $foo: $!" unless open(FOO,$foo);
  6639.  
  6640.          because the second way  hides  the  main  point  of  the
  6641.          statement in a modifier.  On the other hand
  6642.  
  6643.               print "Starting analysis\n" if $verbose;
  6644.  
  6645.          is better than
  6646.  
  6647.               $verbose && print "Starting analysis\n";
  6648.  
  6649.          since the main point isn't whether the user typed -v  or
  6650.          not.
  6651.  
  6652.          Similarly, just because  an  operator  lets  you  assume
  6653.          default arguments doesn't mean that you have to make use
  6654.          of the defaults.  The defaults are there for  lazy  sys-
  6655.          tems programmers writing one-shot programs.  If you want
  6656.          your program to  be  readable,  consider  supplying  the
  6657.          argument.
  6658.  
  6659.          Along  the  same  lines,  just  because  you  _c_a_n   omit
  6660.  
  6661.  
  6662.  
  6663. Consensys Computer Inc.                                       101
  6664.  
  6665.  
  6666.  
  6667.  
  6668.  
  6669.  
  6670. PERL(1)                  USER COMMANDS                    PERL(1)
  6671.  
  6672.  
  6673.  
  6674.          parentheses  in  many places doesn't mean that you ought
  6675.          to:
  6676.  
  6677.               return print reverse sort num values array;
  6678.               return print(reverse(sort num (values(%array))));
  6679.  
  6680.          When in doubt, parenthesize.  At the very least it  will
  6681.          let some poor schmuck bounce on the % key in vi.
  6682.  
  6683.          Even if you aren't in doubt, consider the mental welfare
  6684.          of  the  person  who has to maintain the code after you,
  6685.          and who will probably put parens in the wrong place.
  6686.  
  6687.      2.  Don't go through silly contortions to exit a loop at the
  6688.          top  or the bottom, when _p_e_r_l provides the "last" opera-
  6689.          tor so you can exit in the middle.  Just  outdent  it  a
  6690.          little to make it more visible:
  6691.  
  6692.              line:
  6693.               for (;;) {
  6694.                   statements;
  6695.               last line if $foo;
  6696.                   next line if /^#/;
  6697.                   statements;
  6698.               }
  6699.  
  6700.  
  6701.      3.  Don't be afraid to use  loop  labels--they're  there  to
  6702.          enhance readability as well as to allow multi-level loop
  6703.          breaks.  See last example.
  6704.  
  6705.      4.  For portability, when using features  that  may  not  be
  6706.          implemented  on  every machine, test the construct in an
  6707.          eval to see if it fails.  If you know  what  version  or
  6708.          patchlevel a particular feature was implemented, you can
  6709.          test $] to see if it will be there.
  6710.  
  6711.      5.  Choose mnemonic identifiers.
  6712.  
  6713.      6.  Be consistent.
  6714.  
  6715.      DDDDeeeebbbbuuuuggggggggiiiinnnngggg
  6716.  
  6717.      If you invoke _p_e_r_l with a ----dddd switch, your script will be run
  6718.      under  a  debugging  monitor.  It will halt before the first
  6719.      executable statement and ask you for a command, such as:
  6720.  
  6721.      h           Prints out a help message.
  6722.  
  6723.      T           Stack trace.
  6724.  
  6725.  
  6726.  
  6727.  
  6728.  
  6729. Consensys Computer Inc.                                       102
  6730.  
  6731.  
  6732.  
  6733.  
  6734.  
  6735.  
  6736. PERL(1)                  USER COMMANDS                    PERL(1)
  6737.  
  6738.  
  6739.  
  6740.      s           Single step.   Executes  until  it  reaches  the
  6741.                  beginning of another statement.
  6742.  
  6743.      n           Next.  Executes over subroutine calls, until  it
  6744.                  reaches the beginning of the next statement.
  6745.  
  6746.      f           Finish.  Executes statements until it  has  fin-
  6747.                  ished the current subroutine.
  6748.  
  6749.      c           Continue.  Executes until the next breakpoint is
  6750.                  reached.
  6751.  
  6752.      c line      Continue to the specified line.  Inserts a  one-
  6753.                  time-only breakpoint at the specified line.
  6754.  
  6755.      <CR>        Repeat last n or s.
  6756.  
  6757.      l min+incr  List incr+1 lines starting at min.   If  min  is
  6758.                  omitted, starts where last listing left off.  If
  6759.                  incr is omitted, previous value of incr is used.
  6760.  
  6761.      l min-max   List lines in the indicated range.
  6762.  
  6763.      l line      List just the indicated line.
  6764.  
  6765.      l           List next window.
  6766.  
  6767.      -           List previous window.
  6768.  
  6769.      w line      List window around line.
  6770.  
  6771.      l subname   List subroutine.  If it's a long  subroutine  it
  6772.                  just lists the beginning.  Use "l" to list more.
  6773.  
  6774.      /pattern/   Regular expression search forward  for  pattern;
  6775.                  the final / is optional.
  6776.  
  6777.      ?pattern?   Regular expression search backward for  pattern;
  6778.                  the final ? is optional.
  6779.  
  6780.      L           List lines that have breakpoints or actions.
  6781.  
  6782.      S           Lists the names of all subroutines.
  6783.  
  6784.      t           Toggle trace mode on or off.
  6785.  
  6786.      b line condition
  6787.                  Set a breakpoint.  If line is  omitted,  sets  a
  6788.                  breakpoint  on the line that is about to be exe-
  6789.                  cuted.  If  a  condition  is  specified,  it  is
  6790.                  evaluated each time the statement is reached and
  6791.                  a breakpoint is taken only if the  condition  is
  6792.  
  6793.  
  6794.  
  6795. Consensys Computer Inc.                                       103
  6796.  
  6797.  
  6798.  
  6799.  
  6800.  
  6801.  
  6802. PERL(1)                  USER COMMANDS                    PERL(1)
  6803.  
  6804.  
  6805.  
  6806.                  true.  Breakpoints may only be set on lines that
  6807.                  begin an executable statement.
  6808.  
  6809.      b subname condition
  6810.                  Set breakpoint at first executable line of  sub-
  6811.                  routine.
  6812.  
  6813.      d line      Delete breakpoint.  If line is omitted,  deletes
  6814.                  the  breakpoint  on the line that is about to be
  6815.                  executed.
  6816.  
  6817.      D           Delete all breakpoints.
  6818.  
  6819.      a line command
  6820.                  Set an action for line.   A  multi-line  command
  6821.                  may be entered by backslashing the newlines.
  6822.  
  6823.      A           Delete all line actions.
  6824.  
  6825.      < command   Set an action to happen  before  every  debugger
  6826.                  prompt.   A multi-line command may be entered by
  6827.                  backslashing the newlines.
  6828.  
  6829.      > command   Set an action to happen after  the  prompt  when
  6830.                  you've just given a command to return to execut-
  6831.                  ing the script.  A  multi-line  command  may  be
  6832.                  entered by backslashing the newlines.
  6833.  
  6834.      V package   List all variables in package.  Default is  main
  6835.                  package.
  6836.  
  6837.      ! number    Redo a debugging command.  If number is omitted,
  6838.                  redoes the previous command.
  6839.  
  6840.      ! -number   Redo the command that  was  that  many  commands
  6841.                  ago.
  6842.  
  6843.      H -number   Display last n commands.  Only  commands  longer
  6844.                  than  one  character  are  listed.  If number is
  6845.                  omitted, lists them all.
  6846.  
  6847.      q or ^D     Quit.
  6848.  
  6849.      command     Execute command as a perl statement.  A  missing
  6850.                  semicolon will be supplied.
  6851.  
  6852.      p expr      Same  as  "print  DB'OUT  expr".    The   DB'OUT
  6853.                  filehandle  is opened to /dev/tty, regardless of
  6854.                  where STDOUT may be redirected to.
  6855.  
  6856.      If you want to modify the debugger, copy perldb.pl from  the
  6857.      perl  library  to  your  current  directory and modify it as
  6858.  
  6859.  
  6860.  
  6861. Consensys Computer Inc.                                       104
  6862.  
  6863.  
  6864.  
  6865.  
  6866.  
  6867.  
  6868. PERL(1)                  USER COMMANDS                    PERL(1)
  6869.  
  6870.  
  6871.  
  6872.      necessary.  (You'll also have to put  -I.  on  your  command
  6873.      line.)   You  can  do  some  customization  by  setting up a
  6874.      .perldb  file  which  contains  initialization  code.    For
  6875.      instance, you could make aliases like these:
  6876.  
  6877.          $DB'alias{'len'} = 's/^len(.*)/p length($1)/';
  6878.          $DB'alias{'stop'} = 's/^stop (at|in)/b/';
  6879.          $DB'alias{'.'} =
  6880.            's/^\./p "\$DB\'sub(\$DB\'line):\t",\$DB\'line[\$DB\'line]/';
  6881.  
  6882.  
  6883.      SSSSeeeettttuuuuiiiidddd SSSSccccrrrriiiippppttttssss
  6884.  
  6885.      _P_e_r_l is designed to make it easy to write secure setuid  and
  6886.      setgid  scripts.  Unlike shells, which are based on multiple
  6887.      substitution passes on each line of the script, _p_e_r_l uses  a
  6888.      more   conventional  evaluation  scheme  with  fewer  hidden
  6889.      "gotchas".   Additionally,  since  the  language  has   more
  6890.      built-in  functionality,  it  has to rely less upon external
  6891.      (and possibly untrustworthy) programs to accomplish its pur-
  6892.      poses.
  6893.  
  6894.      In an unpatched 4.2 or 4.3bsd  kernel,  setuid  scripts  are
  6895.      intrinsically  insecure, but this kernel feature can be dis-
  6896.      abled.  If it is, _p_e_r_l can emulate  the  setuid  and  setgid
  6897.      mechanism  when  it notices the otherwise useless setuid/gid
  6898.      bits on perl scripts.  If the kernel feature isn't disabled,
  6899.      _p_e_r_l  will  complain  loudly  that  your  setuid  script  is
  6900.      insecure.  You'll need to either disable the  kernel  setuid
  6901.      script feature, or put a C wrapper around the script.
  6902.  
  6903.      When _p_e_r_l is executing a setuid  script,  it  takes  special
  6904.      precautions  to  prevent  you  from falling into any obvious
  6905.      traps.  (In some ways, a perl script is more secure than the
  6906.      corresponding   C  program.)   Any  command  line  argument,
  6907.      environment variable, or input is marked as  "tainted",  and
  6908.      may not be used, directly or indirectly, in any command that
  6909.      invokes a subshell, or in any command that  modifies  files,
  6910.      directories  or  processes.  Any variable that is set within
  6911.      an expression that has previously referenced a tainted value
  6912.      also becomes tainted (even if it is logically impossible for
  6913.      the tainted value to influence the variable).  For example:
  6914.  
  6915.           $foo = shift;            # $foo is tainted
  6916.           $bar = $foo,'bar';       # $bar is also tainted
  6917.           $xxx = <>;               # Tainted
  6918.           $path = $ENV{'PATH'};    # Tainted, but see below
  6919.           $abc = 'abc';            # Not tainted
  6920.  
  6921.  
  6922.  
  6923.  
  6924.  
  6925.  
  6926.  
  6927. Consensys Computer Inc.                                       105
  6928.  
  6929.  
  6930.  
  6931.  
  6932.  
  6933.  
  6934. PERL(1)                  USER COMMANDS                    PERL(1)
  6935.  
  6936.  
  6937.  
  6938.           system "echo $foo";      # Insecure
  6939.           system "/bin/echo", $foo;     # Secure (doesn't use sh)
  6940.           system "echo $bar";      # Insecure
  6941.           system "echo $abc";      # Insecure until PATH set
  6942.  
  6943.           $ENV{'PATH'} = '/bin:/usr/bin';
  6944.           $ENV{'IFS'} = '' if $ENV{'IFS'} ne '';
  6945.  
  6946.           $path = $ENV{'PATH'};    # Not tainted
  6947.           system "echo $abc";      # Is secure now!
  6948.  
  6949.           open(FOO,"$foo");        # OK
  6950.           open(FOO,">$foo");       # Not OK
  6951.  
  6952.           open(FOO,"echo $foo|");  # Not OK, but...
  6953.           open(FOO,"-|") || exec 'echo', $foo;    # OK
  6954.  
  6955.           $zzz = `echo $foo`;      # Insecure, zzz tainted
  6956.  
  6957.           unlink $abc,$foo;        # Insecure
  6958.           umask $foo;              # Insecure
  6959.  
  6960.           exec "echo $foo";        # Insecure
  6961.           exec "echo", $foo;       # Secure (doesn't use sh)
  6962.           exec "sh", '-c', $foo;   # Considered secure, alas
  6963.  
  6964.      The taintedness is associated with  each  scalar  value,  so
  6965.      some elements of an array can be tainted, and others not.
  6966.  
  6967.      If you try to do something insecure, you will  get  a  fatal
  6968.      error   saying   something  like  "Insecure  dependency"  or
  6969.      "Insecure PATH".  Note that you can still write an  insecure
  6970.      system  call or exec, but only by explicitly doing something
  6971.      like the last example above.  You can also bypass the taint-
  6972.      ing mechanism by referencing subpatterns--_p_e_r_l presumes that
  6973.      if you reference a substring using $1,  $2,  etc,  you  knew
  6974.      what you were doing when you wrote the pattern:
  6975.  
  6976.           $ARGV[0] =~ /^-P(\w+)$/;
  6977.           $printer = $1;      # Not tainted
  6978.  
  6979.      This is fairly secure since \w+ doesn't  match  shell  meta-
  6980.      characters.   Use  of  .+ would have been insecure, but _p_e_r_l
  6981.      doesn't check for that, so you must  be  careful  with  your
  6982.      patterns.   This  is  the ONLY mechanism for untainting user
  6983.      supplied filenames if you want to do file operations on them
  6984.      (unless you make $> equal to $<).
  6985.  
  6986.      It's also possible to get into trouble with other operations
  6987.      that don't care whether they use tainted values.  Make judi-
  6988.      cious use of the  file  tests  in  dealing  with  any  user-
  6989.      supplied  filenames.  When possible, do opens and such after
  6990.  
  6991.  
  6992.  
  6993. Consensys Computer Inc.                                       106
  6994.  
  6995.  
  6996.  
  6997.  
  6998.  
  6999.  
  7000. PERL(1)                  USER COMMANDS                    PERL(1)
  7001.  
  7002.  
  7003.  
  7004.      setting $> = $<.  _P_e_r_l  doesn't  prevent  you  from  opening
  7005.      tainted  filenames for reading, so be careful what you print
  7006.      out.  The tainting mechanism is intended to  prevent  stupid
  7007.      mistakes, not to remove the need for thought.
  7008.  
  7009. MMMMSSSS----DDDDOOOOSSSS CCCCOOOONNNNSSSSIIIIDDDDEEEERRRRAAAATTTTIIIIOOOONNNNSSSS
  7010.      This section describes the MS-DOS version of  _p_e_r_l.   MS-DOS
  7011.      _p_e_r_l  has  been  tested with MS-DOS versions 3.2, 3.3, 4.01,
  7012.      and 5.0, and should work with 2.0 or  higher.   640  K-bytes
  7013.      are needed to get anything done.  MS-DOS 5.0 running in high
  7014.      memory is recommended.
  7015.  
  7016.      CCCCoooommmmmmmmaaaannnndddd----LLLLiiiinnnneeee AAAArrrrgggguuuummmmeeeennnnttttssss iiiinnnn MMMMSSSS----DDDDOOOOSSSS
  7017.  
  7018.      MS-DOS _p_e_r_l recognizes the calling conventions  of  the  MKS
  7019.      toolkit, accepting MKS-style arguments and passing MKS-style
  7020.      arguments to subprocesses.  (The MKS toolkit  is  a  set  of
  7021.      Unix-like  tools for MS-DOS, sold by Mortice Kern Systems of
  7022.      Waterloo, Ontario.)  The  MKS  tools  support  an  expanded,
  7023.      upwardly  compatible  argument-passing  convention  by which
  7024.      several kilobytes of pre-globbed arguments can be passed  to
  7025.      a  process,  resulting  in  Unix-like invocation.  Arbitrary
  7026.      arguments, for example ----eeee commands, can be enclosed in  sin-
  7027.      gle quotes just as in Unix.  This works even if MKSARGS (see
  7028.      the section on the environment below) is not set.
  7029.  
  7030.      When invoked from a non-MKS tool with MKS  tooling  present,
  7031.      _p_e_r_l  will use the MKS glob program (see GLOB in the section
  7032.      on the MS-DOS environment, below) to expand the wildcards.
  7033.  
  7034.      When run on a system that doesn't have MKS tools, _p_e_r_l  will
  7035.      attempt  to expand wildcards it sees in the argument list by
  7036.      using Microsoft's globbing code.  This  code  is  not  smart
  7037.      enough  to  handle  single quote marks, making the ----eeee switch
  7038.      almost useless.
  7039.  
  7040.      Unix does globbing differently than MS-DOS.  Under Unix  and
  7041.      MKS,  "abc*"  matches abc.c,  Under DOS, though, the * won't
  7042.      match "."  The MKS tools use the former interpretation;  the
  7043.      perlglob.exe  program distributed with perl and the globbing
  7044.      built in to perl.exe use the  latter.   (Don't  install  the
  7045.      distributed perlglob.exe if you are using the MKS tools.)
  7046.  
  7047.      FFFFiiiilllleeee nnnnaaaammmmeeeessss iiiinnnn MMMMSSSS----DDDDOOOOSSSS
  7048.  
  7049.      _P_e_r_l scripts should use forward slashes to delimit path name
  7050.      components. (C programmers should note that most MS-DOS com-
  7051.      pilers support this,  too.)   MS-DOS  _p_e_r_l  will  work  with
  7052.      backslashes,  but  they  make code unnecessarily messy since
  7053.      they must be doubled any time they might be  interpreted  as
  7054.      an escape sequence.  Subprograms may or may not like forward
  7055.      slashes: most programs compiled  from  C  source  like  them
  7056.  
  7057.  
  7058.  
  7059. Consensys Computer Inc.                                       107
  7060.  
  7061.  
  7062.  
  7063.  
  7064.  
  7065.  
  7066. PERL(1)                  USER COMMANDS                    PERL(1)
  7067.  
  7068.  
  7069.  
  7070.      fine, but command.com won't take them as command names or as
  7071.      file names in "internal" commands.  Slashes can be  reversed
  7072.      before  invoking  a  subprocess  using  the  perl substution
  7073.      features.  Inside _p_e_r_l, the following name the same file:
  7074.  
  7075.           "c:/new/report"
  7076.           "c:\\new\\report"
  7077.           'c:/new/report'
  7078.           'c:\new\report'
  7079.  
  7080.      Drive prefixes are optional.  If omitted, the file is sought
  7081.      on the current drive.
  7082.  
  7083.      TTTThhhheeee MMMMSSSS----DDDDOOOOSSSS EEEEnnnnvvvviiiirrrroooonnnnmmmmeeeennnntttt
  7084.  
  7085.      MS-DOS _p_e_r_l uses a number of environment variables not  used
  7086.      by  Unix  _p_e_r_l.  This allows customizing the MS-DOS version,
  7087.      which can be widely distributed in  executable  form.   (Not
  7088.      everyone  who  wishes to use _p_e_r_l on MS-DOS has the tools to
  7089.      build it from the source code.)  Directory and file names in
  7090.      the  environment  can  be  delimited  with  forward  or back
  7091.      slashes.  Environment variables are  interpreted  when  they
  7092.      are needed.  (Exception: creation of TMP from TMPDIR is done
  7093.      at startup.)  Thus the perl script  can  change  them.   For
  7094.      example, if a huge "pipe" file is to be created, and there's
  7095.      room on the hard disk (c:) but not the usual TMP, which is a
  7096.      RAM disk, you can write:
  7097.  
  7098.           ENV{'TMP'} = "c:/tmp";
  7099.           open (HANDLE, "program|");
  7100.  
  7101.      PATH        This is the semicolon-separated path list.   The
  7102.                  current   directory  is  searched  first  unless
  7103.                  MKSARGS is defined and MKS support  is  compiled
  7104.                  in,  in  which  case  the  current  directory is
  7105.                  searched only in response to an explicit "."  or
  7106.                  null  path  component.   (This applies to the ----SSSS
  7107.                  switch as well.)
  7108.  
  7109.      MKSARGS     Set to 1 enable all MKSisms.  The MKS tools  can
  7110.                  assume  that the other pieces of the toolkit are
  7111.                  lying around, but _p_e_r_l can't.  (It  may  be  the
  7112.                  only  MKS-compatible  program  on a system.)  If
  7113.                  have have the MKS tools,  you  should  set  this
  7114.                  variable.   Perl will recognize and generate MKS
  7115.                  compatible arguments in any  case,  but  without
  7116.                  the  switch  will default SLASHC to "-c" instead
  7117.                  of "-ce", will fail to run MKS  glob,  and  will
  7118.                  run  perl's  glob  instead  of the Korn shell to
  7119.                  expand expressions like <*.c>.
  7120.  
  7121.      ROOTDIR     Full  drive  and  path  where  MKS  toolkit   is
  7122.  
  7123.  
  7124.  
  7125. Consensys Computer Inc.                                       108
  7126.  
  7127.  
  7128.  
  7129.  
  7130.  
  7131.  
  7132. PERL(1)                  USER COMMANDS                    PERL(1)
  7133.  
  7134.  
  7135.  
  7136.                  installed.
  7137.                   Example,  "c:/mks"  or  "d:/".   Typically   is
  7138.                  already  set  in  MKS environment.  Used only if
  7139.                  MKSARGS is set and GLOB is not.  See GLOB.
  7140.  
  7141.      TMP         First  choice   for   temporary   files,   e.g.,
  7142.                  'h:\tmp'.   If not set, uses TMPDIR (see below),
  7143.                  if that's not  set,  the  current  directory  is
  7144.                  used.  Swapping also goes here unless EXESWAP is
  7145.                  defined.  Temporary files are pseudo-pipes,  the
  7146.                  swap file, and the ----eeee file.
  7147.  
  7148.      TMPDIR      If TMPDIR is set and TMP is not,  the  following
  7149.                  is done internally:
  7150.  
  7151.                       ( $ENV{'TMP'} = $ENV{'TMPDIR'} ) =~ s,/,\\,g;
  7152.  
  7153.                  (Backslashes  are  reversed  as  a  gesture   to
  7154.                  intolerant  decendents  of  the  perl  process.)
  7155.                  Creation of $ENV{'TMP'} from  $ENV{'TMPDIR'}  is
  7156.                  done  at  perl.exe  startup.   Note that the MKS
  7157.                  tools use TMPDIR as a first choice; as a gesture
  7158.                  of  compatibility for non-MKS users, here, it is
  7159.                  a second choice.
  7160.  
  7161.      EXESWAP     First choice for swap out file location.  A  RAM
  7162.                  disk  is  a  nice  choice.   TMP is used if this
  7163.                  isn't set.  (See also TMPDIR).   The  swap  file
  7164.                  created  the  first time swapping is invoked and
  7165.                  is left open until perl exits or does  an  exec.
  7166.                  Set to ".off" (note illegal DOS name) to inhibit
  7167.                  swapping-- useful for speedy  running  of  small
  7168.                  subprocesses.   This feature (inhibition) can be
  7169.                  turned on and off.  The following  example  runs
  7170.                  "ls"  using  "e:/tmp"  as  the directory for the
  7171.                  swap file.  It then runs  "who,"  with  swapping
  7172.                  disabled.   Finally,  it runs "ps" with swapping
  7173.                  re-enabled.  Note that $ENV{'EXESWAP'} is set to
  7174.                  'yes'  but anything other than '.off' would have
  7175.                  sufficed.
  7176.  
  7177.                       $ENV{'EXESWAP'} = 'e:/tmp';
  7178.                       system "ls";
  7179.                       $ENV{'EXESWAP'} = '.off';
  7180.                       system "who";
  7181.                       $ENV{'EXESWAP'} = 'yes';
  7182.                       system "ps";
  7183.  
  7184.      GLOB        First choice  for  MKS  globbing  program:  full
  7185.                  path,    name,    and    extension.     Example:
  7186.                  "d:/mks/etc/glob.exe".  The perl  globbing  pro-
  7187.                  gram  (used  for  <*.c>  expansion) is found, as
  7188.  
  7189.  
  7190.  
  7191. Consensys Computer Inc.                                       109
  7192.  
  7193.  
  7194.  
  7195.  
  7196.  
  7197.  
  7198. PERL(1)                  USER COMMANDS                    PERL(1)
  7199.  
  7200.  
  7201.  
  7202.                  before, via the  PATH.   Used  only  in  an  MKS
  7203.                  environment, and then only when perl is run from
  7204.                  a non-MKS program.  Ignored if MKS support  com-
  7205.                  piled out.
  7206.  
  7207.      SHELL       Full path name and extension of the  shell  used
  7208.                  used for subprocesses when wildcard expansion is
  7209.                  required, e.g., "c:/mks/bin/sh.exe".   If  unde-
  7210.                  fined,  COMSPEC  is used.  Presumably this could
  7211.                  be the MKS korn shell, but  it  can  be  another
  7212.                  shell  (e.g.,  4DOS) and thus SHELL is inspected
  7213.                  even if MKS support is compiled out.
  7214.  
  7215.      COMSPEC     Full path name of DOS command interpreter, e.g.,
  7216.                  If  not  found,  '\command.com' is used.  (It is
  7217.                  bad practice to allow COMSPEC to default  or  to
  7218.                  have  it  have  anything other than a full drive
  7219.                  and path name.  You  don't  want  your  programs
  7220.                  looking for command.com on alternate drives.)
  7221.  
  7222.      METACHAR    List of characters that  are  metacharacters  to
  7223.                  the  SHELL  or  COMPSPEC.   Used to determine if
  7224.                  command can be run directly  or  if  a  subshell
  7225.                  must be invoked.  If undefined, \|<> is used for
  7226.                  COMSPEC and *"?<>][`'\ for SHELL.
  7227.  
  7228.      SLASHC      The  shell  option  for  invoking   a   command.
  7229.                  Defaults:  /c for COMSPEC, MS-DOS version 4.x or
  7230.                  better [sic] where _s is  the  switch  character,
  7231.                  for COMSPEC, DOS < 4.0; -ce for SHELL if MKSARGS
  7232.                  is set.  (The -e needed  to  get  the  MKS  Korn
  7233.                  shell  to  return  the  status  properly).   The
  7234.                  default is -c for  other  SHELLs.   (This  is  a
  7235.                  guess.)
  7236.  
  7237.      PERLLIB     Directory(ies)    containing    perl    library.
  7238.                  Defaults  to  /usr/local/lib/perl.   Directories
  7239.                  are separated as in PATH:  semicolons in MS-DOS,
  7240.                  colons  in  Unix.   For  the -P switch, only the
  7241.                  first PERLLIB  directory  (or  the  default,  if
  7242.                  there's no PERLLIB) is tried.
  7243.  
  7244.      TTTTyyyyppppiiiiccccaaaallll MMMMKKKKSSSS sssseeeettttuuuupppp ((((pppprrrrooooffffiiiilllleeee....kkkksssshhhh))))
  7245.  
  7246.      # If you're using the MKS stuff, you probably don't have
  7247.      # to do anything other than set MKSARGS and PERLLIB.
  7248.  
  7249.      export MKSARGS=1
  7250.      # ROOTDIR set by init process or etc.rc or here.
  7251.      export TMPDIR=e:/tmp
  7252.      # EXESWAP left to default to $TMPDIR
  7253.      # GLOB left to default to $ROOTDIR/etc/glob.exe
  7254.  
  7255.  
  7256.  
  7257. Consensys Computer Inc.                                       110
  7258.  
  7259.  
  7260.  
  7261.  
  7262.  
  7263.  
  7264. PERL(1)                  USER COMMANDS                    PERL(1)
  7265.  
  7266.  
  7267.  
  7268.      # SHELL set by init process or here.
  7269.      # COMSPEC not used by perl.exe but probably defined for other uses.
  7270.      # METACHAR not defined, left to default.
  7271.      export PERLLIB='c:/lib/perl;d:/usr/me/myperlib'
  7272.  
  7273.      TTTTyyyyppppiiiiccccaaaallll nnnnoooonnnn----MMMMKKKKSSSS sssseeeettttuuuupppp ((((AAAAUUUUTTTTOOOOEEEEXXXXEEEECCCC....BBBBAAAATTTT))))
  7274.  
  7275.      Rem You probably don't need to do anything except set TMP,
  7276.      Rem which you may be doing anyway.
  7277.  
  7278.      Rem MKSARGS not set
  7279.      Rem ROOTDIR not used
  7280.      set TMP=d:\tmp
  7281.      Rem EXESWAP left to default to TMP
  7282.      Rem GLOB not used
  7283.      Rem SHELL not set
  7284.      Rem COMPEC set by config.sys SHELL command or by MS-DOS startup.
  7285.      Rem METACHAR not defined, left to default.
  7286.      set PERLLIB=c:/lib/perl;d:/usr/me/myperlib'
  7287.  
  7288.      GGGGlllloooobbbbbbbbiiiinnnngggg <<<<>>>> EEEExxxxpppprrrreeeessssssssiiiioooonnnnssss oooonnnn MMMMSSSS----DDDDOOOOSSSS
  7289.  
  7290.      Expressions like <*.c> are expanded by a subshell  in  Unix.
  7291.      On MS-DOS there are two cases.  If MKSARGS is defined in the
  7292.      environment and MKS support is compiled  in,  the  SHELL  is
  7293.      used,  running  _e_c_h_o piped to _t_r as with the Bourne shell on
  7294.      Unix _p_e_r_l.  Otherwise, the supplied perlglob.exe program  is
  7295.      run.   This  program simply takes the supplied command line,
  7296.      DOS-globs it, and writes the result, to the _p_e_r_l process via
  7297.      a "pipe."
  7298.  
  7299.      RRRRuuuunnnnnnnniiiinnnngggg SSSSuuuubbbbpppprrrroooocccceeeesssssssseeeessss oooonnnn MMMMSSSS----DDDDOOOOSSSS
  7300.  
  7301.      _P_e_r_l will by default swap itself out almost entirely when it
  7302.      runs  a  subprocess  other  than MKS GLOB.  (See the EXESWAP
  7303.      environment variable).  The swap file  is  opened  when  the
  7304.      first subprocess is run and is left open until _p_e_r_l exits or
  7305.      does an IR exec .  The command line to be run is scanned for
  7306.      METACHARacters  as  described above.  If none are found, the
  7307.      subcommand is invoked  directly.   If  metacharacter(s)  are
  7308.      found, a SHELL or COMSPEC is invoked to run the command.
  7309.  
  7310.      Use of a single |||| in a open() command does not constitute  a
  7311.      metacharcter:   this  is a directive to perl to open a pipe.
  7312.      The following, too, has no SHELL  metacharacters  since  the
  7313.      subprocess is simply pwd:
  7314.  
  7315.      chop($direct = `pwd`);
  7316.  
  7317.      Beware of MS-DOS "internal" commands; i.e., those  that  are
  7318.      built   into   command.com.   Examples  are  DIR  and  COPY.
  7319.      COMMAND.COM users can use these directly if the command  has
  7320.  
  7321.  
  7322.  
  7323. Consensys Computer Inc.                                       111
  7324.  
  7325.  
  7326.  
  7327.  
  7328.  
  7329.  
  7330. PERL(1)                  USER COMMANDS                    PERL(1)
  7331.  
  7332.  
  7333.  
  7334.      METACHARacters;   if   not,  you  must  invoke  an  explicit
  7335.      command.com.  In the first example below, '>' is a metachar-
  7336.      acter.   In  the second example, there are no metacharacters
  7337.      and so the internal "ver" command must be run with an expli-
  7338.      clit COMSPEC.
  7339.  
  7340.           system "dir >my.fil";
  7341.           system "$ENV{'COMSPEC'} /c ver";
  7342.  
  7343.      Users of SHELLs other than COMMAND.COM must use  the  second
  7344.      format to access "internal" commands.
  7345.  
  7346.      Be aware that no wild card expansion is going to be done  by
  7347.      command.com usless you're using one of the built-in commands
  7348.      that does it (e.g., COPY).  You can use <> expansion to  get
  7349.      around  this.   Even those who have fancy SHELLs should take
  7350.      note of this, since having _p_e_r_l run the SHELL and  then  the
  7351.      command  may  use  less  memory than if perl runs the $SHELL
  7352.      which runs the command:
  7353.  
  7354.           $files = <*.c>;
  7355.           `the_com $files`;
  7356.  
  7357.  
  7358. EEEENNNNVVVVIIIIRRRROOOONNNNMMMMEEEENNNNTTTT
  7359.      _P_e_r_l uses PATH in executing subprocesses, and in finding the
  7360.      script  if -S is used.  HOME or LOGDIR are used if chdir has
  7361.      no argument.  _P_e_r_l, but not _t_a_i_n_t_p_e_r_l, will add  PERLLIB  to
  7362.      @INC.   PERLLIB  is  syntactically similar to PATH:  it con-
  7363.      tains a list of directories.
  7364.  
  7365.      Apart from these, Unix _p_e_r_l uses no  environment  variables,
  7366.      except  to make them available to the script being executed,
  7367.      and to child processes.  (MS-DOS _p_e_r_l makes heavy use of the
  7368.      environment;  refer to the section on MS-DOS consdirations.)
  7369.  
  7370.      Scripts running setuid would do well to execute the  follow-
  7371.      ing  lines  before  doing anything else, just to keep people
  7372.      honest:
  7373.  
  7374.          $ENV{'PATH'} = '/bin:/usr/bin';    # or whatever you need
  7375.          $ENV{'SHELL'} = '/bin/sh' if $ENV{'SHELL'} ne '';
  7376.          $ENV{'IFS'} = '' if $ENV{'IFS'} ne '';
  7377.  
  7378.  
  7379. AAAAUUUUTTTTHHHHOOOORRRR
  7380.      Larry Wall <lwall@netlabs.com>
  7381.      MS-DOS port by Diomidis Spinellis <dds@cc.ic.ac.uk> and  Len
  7382.      Reed <holos0!lbr@gatech.edu>
  7383.  
  7384. FFFFIIIILLLLEEEESSSS
  7385.      /tmp/perl-eXXXXXX   temporary   file   for   ----eeee    commands.
  7386.  
  7387.  
  7388.  
  7389. Consensys Computer Inc.                                       112
  7390.  
  7391.  
  7392.  
  7393.  
  7394.  
  7395.  
  7396. PERL(1)                  USER COMMANDS                    PERL(1)
  7397.  
  7398.  
  7399.  
  7400.      $TMP/plXXXXXX       temporary file for ----eeee commands (MS-DOS).
  7401.      $TMP/swpXXXXX       swap            file            (MS-DOS)
  7402.      $TMP/ppXXXXXX       "pipe" files (MS-DOS)
  7403.  
  7404. SSSSEEEEEEEE AAAALLLLSSSSOOOO
  7405.      a2p  awk to perl translator
  7406.      s2p  sed to perl translator
  7407.  
  7408. DDDDIIIIAAAAGGGGNNNNOOOOSSSSTTTTIIIICCCCSSSS
  7409.      Compilation errors will tell you  the  line  number  of  the
  7410.      error,  with  an  indication of the next token or token type
  7411.      that was to be examined.  (In the case of a script passed to
  7412.      _p_e_r_l via ----eeee switches, each ----eeee is counted as one line.)
  7413.  
  7414.      Setuid scripts have additional constraints that can  produce
  7415.      error  messages such as "Insecure dependency".  See the sec-
  7416.      tion on setuid scripts.
  7417.  
  7418. TTTTRRRRAAAAPPPPSSSS
  7419.      Accustomed _a_w_k users should take special note of the follow-
  7420.      ing:
  7421.  
  7422.      *   Semicolons are required after all simple  statements  in
  7423.          _p_e_r_l.  Newline is not a statement delimiter.
  7424.  
  7425.      *   Curly brackets are required on ifs and whiles.
  7426.  
  7427.      *   Variables begin with $ or @ in _p_e_r_l.
  7428.  
  7429.      *   Arrays index from 0 unless you set $[.  Likewise  string
  7430.          positions in substr() and index().
  7431.  
  7432.      *   You have to decide whether your  array  has  numeric  or
  7433.          string indices.
  7434.  
  7435.      *   Associative array values do not  spring  into  existence
  7436.          upon mere reference.
  7437.  
  7438.      *   You have to decide whether you want  to  use  string  or
  7439.          numeric comparisons.
  7440.  
  7441.      *   Reading an input line does not split it  for  you.   You
  7442.          get  to  split  it  yourself to an array.  And the _s_p_l_i_t
  7443.          operator has different arguments.
  7444.  
  7445.      *   The current input line is normally in $_,  not  $0.   It
  7446.          generally  does  not  have the newline stripped.  ($0 is
  7447.          the name of the program executed.)
  7448.  
  7449.      *   $<digit> does not refer to  fields--it  refers  to  sub-
  7450.          strings matched by the last match pattern.
  7451.  
  7452.  
  7453.  
  7454.  
  7455. Consensys Computer Inc.                                       113
  7456.  
  7457.  
  7458.  
  7459.  
  7460.  
  7461.  
  7462. PERL(1)                  USER COMMANDS                    PERL(1)
  7463.  
  7464.  
  7465.  
  7466.      *   The _p_r_i_n_t  statement  does  not  add  field  and  record
  7467.          separators unless you set $, and $\.
  7468.  
  7469.      *   You must open your files before you print to them.
  7470.  
  7471.      *   The range operator  is  "..",  not  comma.   (The  comma
  7472.          operator works as in C.)
  7473.  
  7474.      *   The match operator is "=~", not "~".  ("~" is the  one's
  7475.          complement operator, as in C.)
  7476.  
  7477.      *   The exponentiation operator is "**", not "^".   ("^"  is
  7478.          the XOR operator, as in C.)
  7479.  
  7480.      *   The concatenation operator is ".", not the null  string.
  7481.          (Using  the  null  string  would  render  "/pat/  /pat/"
  7482.          unparsable, since the third slash would  be  interpreted
  7483.          as  a division operator--the tokener is in fact slightly
  7484.          context sensitive for operators like /, ?, and  <.   And
  7485.          in fact, . itself can be the beginning of a number.)
  7486.  
  7487.      *   _N_e_x_t, _e_x_i_t and _c_o_n_t_i_n_u_e work differently.
  7488.  
  7489.      *   The following variables work differently
  7490.  
  7491.                 Awk               Perl
  7492.                 ARGC              $#ARGV
  7493.                 ARGV[0]           $0
  7494.                 FILENAME          $ARGV
  7495.                 FNR               $. - something
  7496.                 FS                (whatever you like)
  7497.                 NF                $#Fld, or some such
  7498.                 NR                $.
  7499.                 OFMT              $#
  7500.                 OFS               $,
  7501.                 ORS               $\
  7502.                 RLENGTH           length($&)
  7503.                 RS                $/
  7504.                 RSTART            length($`)
  7505.                 SUBSEP            $;
  7506.  
  7507.  
  7508.      *   When in doubt, run the _a_w_k construct through a2p and see
  7509.          what it gives you.
  7510.  
  7511.      Cerebral C programmers should take note of the following:
  7512.  
  7513.      *   Curly brackets are required on ifs and whiles.
  7514.  
  7515.      *   You should use "elsif" rather than "else if"
  7516.  
  7517.      *   _B_r_e_a_k and _c_o_n_t_i_n_u_e become _l_a_s_t and _n_e_x_t, respectively.
  7518.  
  7519.  
  7520.  
  7521. Consensys Computer Inc.                                       114
  7522.  
  7523.  
  7524.  
  7525.  
  7526.  
  7527.  
  7528. PERL(1)                  USER COMMANDS                    PERL(1)
  7529.  
  7530.  
  7531.  
  7532.      *   There's no switch statement.
  7533.  
  7534.      *   Variables begin with $ or @ in _p_e_r_l.
  7535.  
  7536.      *   Printf does not implement *.
  7537.  
  7538.      *   Comments begin with #, not /*.
  7539.  
  7540.      *   You can't take the address of anything.
  7541.  
  7542.      *   ARGV must be capitalized.
  7543.  
  7544.      *   The "system" calls link,  unlink,  rename,  etc.  return
  7545.          nonzero for success, not 0.
  7546.  
  7547.      *   Signal handlers deal with signal names, not numbers.
  7548.  
  7549.      Seasoned _s_e_d programmers should take note of the following:
  7550.  
  7551.      *   Backreferences in substitutions use $ rather than \.
  7552.  
  7553.      *   The pattern matching metacharacters (, ), and |  do  not
  7554.          have backslashes in front.
  7555.  
  7556.      *   The range operator is .. rather than comma.
  7557.  
  7558.      Sharp shell programmers should take note of the following:
  7559.  
  7560.      *   The  backtick  operator  does  variable   interpretation
  7561.          without  regard  to the presence of single quotes in the
  7562.          command.
  7563.  
  7564.      *   The backtick operator does no translation of the  return
  7565.          value, unlike csh.
  7566.  
  7567.      *   Shells (especially csh) do several levels  of  substitu-
  7568.          tion  on each command line.  _P_e_r_l does substitution only
  7569.          in certain constructs such as double quotes,  backticks,
  7570.          angle brackets and search patterns.
  7571.  
  7572.      *   Shells interpret scripts a little bit at a  time.   _P_e_r_l
  7573.          compiles the whole program before executing it.
  7574.  
  7575.      *   The arguments are available via @ARGV, not $1, $2, etc.
  7576.  
  7577.      *   The environment is not automatically made  available  as
  7578.          variables.
  7579.  
  7580. EEEERRRRRRRRAAAATTTTAAAA AAAANNNNDDDD AAAADDDDDDDDEEEENNNNDDDDAAAA
  7581.      The Perl book, _P_r_o_g_r_a_m_m_i_n_g _P_e_r_l , has  the  following  omis-
  7582.      sions and goofs.
  7583.  
  7584.  
  7585.  
  7586.  
  7587. Consensys Computer Inc.                                       115
  7588.  
  7589.  
  7590.  
  7591.  
  7592.  
  7593.  
  7594. PERL(1)                  USER COMMANDS                    PERL(1)
  7595.  
  7596.  
  7597.  
  7598.      On page 5, the examples which read
  7599.  
  7600.           eval "/usr/bin/perl
  7601.  
  7602.      should read
  7603.  
  7604.           eval "exec /usr/bin/perl
  7605.  
  7606.  
  7607.      On page 195, the equivalent to the System V sum program only
  7608.      works for very small files.  To do larger files, use
  7609.  
  7610.           undef $/;
  7611.           $checksum = unpack("%32C*",<>) % 32767;
  7612.  
  7613.  
  7614.      The  descriptions  of  alarm  and  sleep  refer  to   signal
  7615.      SIGALARM.  These should refer to SIGALRM.
  7616.  
  7617.      The ----0000 switch to set the initial value of $/  was  added  to
  7618.      Perl after the book went to press.
  7619.  
  7620.      The ----llll switch now does automatic line ending processing.
  7621.  
  7622.      The qx// construct is now a synonym for backticks.
  7623.  
  7624.      $0 may now be assigned to set the argument displayed  by  _p_s
  7625.      (_1).
  7626.  
  7627.      The new @###.## format was  omitted  accidentally  from  the
  7628.      description on formats.
  7629.  
  7630.      It wasn't known at press time that  s///ee  caused  multiple
  7631.      evaluations  of  the  replacement expression.  This is to be
  7632.      construed as a feature.
  7633.  
  7634.      (LIST) x $count now does array replication.
  7635.  
  7636.      There is now no limit on the number of parentheses in a reg-
  7637.      ular expression.
  7638.  
  7639.      In double-quote context, more escapes are supported: \e, \a,
  7640.      \x1b,  \c[,  \l,  \L,  \u,  \U, \E.  The latter five control
  7641.      up/lower case translation.
  7642.  
  7643.      The $$$$//// variable may now be set to a  multi-character  delim-
  7644.      iter.
  7645.  
  7646.      There is now a g modifier on ordinary pattern matching  that
  7647.      causes  it  to  iterate  through  a  string finding multiple
  7648.      matches.
  7649.  
  7650.  
  7651.  
  7652.  
  7653. Consensys Computer Inc.                                       116
  7654.  
  7655.  
  7656.  
  7657.  
  7658.  
  7659.  
  7660. PERL(1)                  USER COMMANDS                    PERL(1)
  7661.  
  7662.  
  7663.  
  7664.      All of the $^X variables are new except for $^T.
  7665.  
  7666.      The  default  top-of-form  format  for  FILEHANDLE  is   now
  7667.      FILEHANDLE_TOP rather than top.
  7668.  
  7669.      The eval {} and sort {} constructs  were  added  in  version
  7670.      4.018.
  7671.  
  7672.      The v and V (little-endian) template options  for  pack  and
  7673.      unpack were added in 4.019.
  7674.  
  7675. BBBBUUUUGGGGSSSS
  7676.      _P_e_r_l is at the mercy of your machine's definitions of  vari-
  7677.      ous operations such as type casting, atof() and sprintf().
  7678.  
  7679.      If your stdio requires an seek  or  eof  between  reads  and
  7680.      writes  on a particular stream, so does _p_e_r_l.  (This doesn't
  7681.      apply to sysread() and syswrite().)
  7682.  
  7683.      While none of the built-in data  types  have  any  arbitrary
  7684.      size  limits (apart from memory size), there are still a few
  7685.      arbitrary limits:  a given identifier may not be longer than
  7686.      255  characters, and no component of your PATH may be longer
  7687.      than 255 if you use -S.
  7688.  
  7689.      _P_e_r_l actually stands  for  Pathologically  Eclectic  Rubbish
  7690.      Lister, but don't tell anyone I said that.
  7691.  
  7692.  
  7693.  
  7694.  
  7695.  
  7696.  
  7697.  
  7698.  
  7699.  
  7700.  
  7701.  
  7702.  
  7703.  
  7704.  
  7705.  
  7706.  
  7707.  
  7708.  
  7709.  
  7710.  
  7711.  
  7712.  
  7713.  
  7714.  
  7715.  
  7716.  
  7717.  
  7718.  
  7719. Consensys Computer Inc.                                       117
  7720.  
  7721.  
  7722.  
  7723.